Consider adding {ReadOnly}SpanMemoryStream types #22838
Labels
api-needs-work
API needs work before it is approved, it is NOT ready for implementation
area-System.Memory
tenet-performance
Performance related issue
Milestone
Just as we have a MemoryStream that works with
byte[]
and an UnmanagedMemoryStream that works with abyte*
and a length, we should support treatingMemory<byte>
andReadOnlyMemory<byte>
as streams.It’s possible we could get away with reimplementing
MemoryStream
on top ofMemory<byte>
, but more than likely this would introduce regressions for at least some existing use cases, and it doesn't work withReadOnlyMemory<byte>
.It would be nice if we could potentially write something ala:
but it's possible that TryGetArray could return false but the wrapped memory not inherently pinned, in which case the UnmanagedMemoryStream case would be wrapping a pointer to memory that could get moved. To pin it and keep track of the pinning, you'd need a wrapper Stream type anyway.
So, we could have two new stream types for these specific types:
The name of BufferStream is unfortunately close to that of BufferedStream, and they mean very different things, but I’m not sure that’s important enough to consider a less meaningful name.
Alternatively, we could hide these behind a factory, e.g.
to keep them from needing to be public.
Especially if we do the latter, we would want to consider either adding TryGetBuffer virtuals to the base Stream class, or introducing an interface that could be queried for and which exposing such methods.
Then for example code that uses Streams and has optimizations when working directly with the underlying data can query for the interface and special-case when the underlying
Buffer<T>
can be accessed, e.g.We could implement this not only on
BufferStream
andReadOnlyBufferStream
, but also onMemoryStream
,UnmanagedMemoryStream
, and even on non-streams, basically anything that can hand out a representation of its internals as buffers.The text was updated successfully, but these errors were encountered: