diff --git a/src/process.tests/PipingTests.cs b/src/process.tests/PipingTests.cs index 1839cc1..571d24f 100644 --- a/src/process.tests/PipingTests.cs +++ b/src/process.tests/PipingTests.cs @@ -1,8 +1,9 @@ // Copyright (c) The Geekeey Authors // SPDX-License-Identifier: EUPL-1.2 -using System.Text; +using System.Buffers; using System.IO.Pipelines; +using System.Text; using Geekeey.Process.Buffered; @@ -619,6 +620,19 @@ internal sealed class PipingTests await Assert.That(output.Length).IsEqualTo(100_000); } + [Test] + public async Task I_can_execute_a_command_and_pipe_the_stdout_to_a_buffer_writer() + { + var output = new ArrayBufferWriter(); + var cmd = new Command(Testing.Fixture.Program.FilePath) + .WithArguments(["generate", "blob", "--length", "100000"]) | + PipeTarget.ToBufferWriter(output); + + await cmd.ExecuteAsync(); + + await Assert.That(output.WrittenCount).IsEqualTo(100_000); + } + [Test] public async Task I_can_execute_a_command_and_pipe_the_stdout_into_multiple_hierarchical_targets() { diff --git a/src/process/PipeSource.cs b/src/process/PipeSource.cs index 096e629..698fd13 100644 --- a/src/process/PipeSource.cs +++ b/src/process/PipeSource.cs @@ -1,8 +1,8 @@ // Copyright (c) The Geekeey Authors // SPDX-License-Identifier: EUPL-1.2 -using System.Text; using System.IO.Pipelines; +using System.Text; namespace Geekeey.Process; diff --git a/src/process/PipeTarget.cs b/src/process/PipeTarget.cs index ff82599..b6e65c6 100644 --- a/src/process/PipeTarget.cs +++ b/src/process/PipeTarget.cs @@ -195,6 +195,29 @@ public partial class PipeTarget }); } + /// + /// Creates a pipe target that writes to the specified buffer writer. + /// + public static PipeTarget ToBufferWriter(IBufferWriter writer) + { + return Create(async (origin, cancellationToken) => + { + using var buffer = MemoryPool.Shared.Rent(MemoryBufferStream.DefaultBufferSize); + + while (true) + { + var read = await origin.ReadAsync(buffer.Memory, cancellationToken); + if (read <= 0) + { + break; + } + + buffer.Memory[..read].Span.CopyTo(writer.GetSpan(read)); + writer.Advance(read); + } + }); + } + /// /// Creates a pipe target that writes to the specified file. ///