Skip to content

Commit

Permalink
Corner case with empty set of tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Jul 13, 2024
1 parent e38245b commit a63d56b
Showing 1 changed file with 32 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using System.Runtime.InteropServices;
using DotNext.Collections.Generic;
using Debug = System.Diagnostics.Debug;

namespace DotNext.Threading.Tasks;

using static Collections.Generic.AsyncEnumerable;

/// <summary>
/// Provides various extension methods for <see cref="TaskCompletionPipe{T}"/> class.
/// </summary>
Expand All @@ -16,7 +19,7 @@ public static class TaskCompletionPipe
/// <returns>The asynchronous consuming collection.</returns>
public static Consumer<T> GetConsumer<T>(this TaskCompletionPipe<Task<T>> pipe)
=> new(pipe);

/// <summary>
/// Gets a collection over tasks to be available as they complete.
/// </summary>
Expand All @@ -25,9 +28,19 @@ public static Consumer<T> GetConsumer<T>(this TaskCompletionPipe<Task<T>> pipe)
/// <returns>A collection over task results to be available as they complete.</returns>
public static Consumer<T> GetConsumer<T>(this ReadOnlySpan<Task<T>> tasks)
{
var pipe = new TaskCompletionPipe<Task<T>>();
pipe.Add(tasks, complete: true);
return new(pipe);
Consumer<T> result;
if (tasks.IsEmpty)
{
result = default;
}
else
{
var pipe = new TaskCompletionPipe<Task<T>>();
pipe.Add(tasks, complete: true);
result = new(pipe);
}

return result;
}

/// <summary>
Expand All @@ -39,9 +52,20 @@ public static Consumer<T> GetConsumer<T>(this ReadOnlySpan<Task<T>> tasks)
public static IAsyncEnumerable<T> Create<T>(ReadOnlySpan<T> tasks)
where T : Task
{
var pipe = new TaskCompletionPipe<T>();
pipe.Add(tasks, complete: true);
return pipe;
IAsyncEnumerable<T> result;

if (tasks.IsEmpty)
{
result = Empty<T>();
}
else
{
var pipe = new TaskCompletionPipe<T>();
pipe.Add(tasks, complete: true);
result = pipe;
}

return result;
}

private static async IAsyncEnumerator<T> GetAsyncEnumerator<T>(TaskCompletionPipe<Task<T>> pipe, uint expectedVersion, CancellationToken token)
Expand Down Expand Up @@ -75,6 +99,6 @@ internal Consumer(TaskCompletionPipe<Task<T>> pipe)
/// <param name="token">The token that can be used to cancel the operation.</param>
/// <returns>The asynchronous enumerator over completed tasks.</returns>
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken token = default)
=> GetAsyncEnumerator<T>(pipe, pipe.Version, token);
=> pipe is null ? Empty<T>().GetAsyncEnumerator(token) : GetAsyncEnumerator<T>(pipe, pipe.Version, token);
}
}

0 comments on commit a63d56b

Please sign in to comment.