Skip to content

Commit 1c04819

Browse files
committed
Added factory method to create combined stream from IEnumerable<Stream> (#255)
1 parent b87212a commit 1c04819

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/DotNext.IO/IO/StreamExtensions.cs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33

44
namespace DotNext.IO;
55

6-
using Collections.Generic;
6+
using Buffers;
7+
using static Runtime.Intrinsics;
78

89
/// <summary>
910
/// Represents high-level read/write methods for the stream.
@@ -58,8 +59,23 @@ public static Stream Combine(this ReadOnlySpan<Stream> streams)
5859
/// <exception cref="ArgumentException"><paramref name="streams"/> is empty.</exception>
5960
public static Stream Combine(this IEnumerable<Stream> streams)
6061
{
61-
using var buffer = streams.Copy();
62-
return Combine(buffer.Span);
62+
// Use buffer to allocate streams on the stack
63+
var buffer = new StreamBuffer();
64+
var writer = new BufferWriterSlim<Stream>(buffer);
65+
66+
Stream result;
67+
try
68+
{
69+
writer.AddAll(streams);
70+
result = Combine(writer.WrittenSpan);
71+
}
72+
finally
73+
{
74+
writer.Dispose();
75+
KeepAlive(in buffer);
76+
}
77+
78+
return result;
6379
}
6480

6581
/// <summary>
@@ -81,4 +97,10 @@ public static Stream AsUnbufferedStream(this SafeFileHandle handle, FileAccess a
8197
? new UnbufferedFileStream(handle, access)
8298
: throw new ArgumentException(ExceptionMessages.FileHandleClosed, nameof(handle));
8399
}
100+
101+
[InlineArray(32)]
102+
private struct StreamBuffer
103+
{
104+
private Stream element0;
105+
}
84106
}

src/DotNext/Buffers/BufferWriterSlim.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ public void Clear(bool reuseBuffer = false)
358358
/// </summary>
359359
/// <param name="collection">A collection of elements.</param>
360360
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is <see langword="null"/>.</exception>
361-
public void Write(IEnumerable<T> collection)
361+
public void AddAll(IEnumerable<T> collection)
362362
{
363363
ArgumentNullException.ThrowIfNull(collection);
364364

0 commit comments

Comments
 (0)