From aeb6598d28682eaf0b2c802232d633b7c05bf1ba Mon Sep 17 00:00:00 2001 From: sakno Date: Tue, 8 Oct 2024 18:24:01 +0300 Subject: [PATCH] Added async singleton collection --- .../Collections/Generic/AsyncEnumerableTests.cs | 7 +++++++ src/DotNext/Collections/Generic/AsyncEnumerable.cs | 9 +++++++++ src/DotNext/Collections/Specialized/SingletonList.cs | 6 +++++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/DotNext.Tests/Collections/Generic/AsyncEnumerableTests.cs b/src/DotNext.Tests/Collections/Generic/AsyncEnumerableTests.cs index 2ebb718aa..6ed4ad29f 100644 --- a/src/DotNext.Tests/Collections/Generic/AsyncEnumerableTests.cs +++ b/src/DotNext.Tests/Collections/Generic/AsyncEnumerableTests.cs @@ -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)); + } } \ No newline at end of file diff --git a/src/DotNext/Collections/Generic/AsyncEnumerable.cs b/src/DotNext/Collections/Generic/AsyncEnumerable.cs index 5eb5bcdf2..50fead5c8 100644 --- a/src/DotNext/Collections/Generic/AsyncEnumerable.cs +++ b/src/DotNext/Collections/Generic/AsyncEnumerable.cs @@ -219,4 +219,13 @@ public static IAsyncEnumerable Throw(Exception e) return new ThrowingEnumerator(e); } + + /// + /// Constructs read-only sequence with a single item in it. + /// + /// An item to be placed into list. + /// Type of list items. + /// Read-only list containing single item. + public static IAsyncEnumerable Singleton(T item) + => new Specialized.SingletonList { Item = item }; } \ No newline at end of file diff --git a/src/DotNext/Collections/Specialized/SingletonList.cs b/src/DotNext/Collections/Specialized/SingletonList.cs index 53b9613fa..4e98514b6 100644 --- a/src/DotNext/Collections/Specialized/SingletonList.cs +++ b/src/DotNext/Collections/Specialized/SingletonList.cs @@ -12,7 +12,7 @@ namespace DotNext.Collections.Specialized; /// /// The type of the element in the list. [StructLayout(LayoutKind.Auto)] -public struct SingletonList : IReadOnlyList, IList, ITuple, IReadOnlySet +public struct SingletonList : IReadOnlyList, IList, ITuple, IReadOnlySet, IAsyncEnumerable { /// /// Represents an enumerator over the collection containing a single element. @@ -145,6 +145,10 @@ readonly IEnumerator IEnumerable.GetEnumerator() readonly IEnumerator IEnumerable.GetEnumerator() => GetEnumerator().ToClassicEnumerator(); + /// + readonly IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken token) + => GetEnumerator().ToAsyncEnumerator(token); + /// /// Converts a value to the read-only list. ///