dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.38k stars 4.75k forks source link

[API Proposal]: Add read/write span methods to UnmanagedMemoryAccessor #107148

Open masonwheeler opened 2 months ago

masonwheeler commented 2 months ago

Background and motivation

https://github.com/dotnet/runtime/issues/27831 added ReadSpan<T> and WriteSpan<T> methods to SafeBuffer, with the explicit intent of surfacing them in UnmanagedMemoryAccessor in a later PR:

The motivation for this is for a later API proposal to add the same methods to UnmanagedMemoryAccessor which will work for memory mapped views.

This was merged 4 years ago, but the later PR appears to have never happened.

API Proposal

Add the following methods to UnmanagedMemoryAccessor:

+        public void ReadSpan<T>(ulong byteOffset, Span<T> buffer) where T : struct
+        public void WriteSpan<T>(ulong byteOffset, ReadOnlySpan<T> data) where T : struct

Their implementations would be similar to the existing ReadArray<T> and WriteArray<T> methods, doing verification and then calling the corresponding methods on _buffer.

API Usage


string text = "Hello, World!";
myMemoryMappedViewAccessor.WriteSpan(MY_OFFSET, text.AsSpan());

Alternative Designs

No response

Risks

None that I can see; the underlying APIs were developed specifically for this purpose.

dotnet-policy-service[bot] commented 2 months ago

Tagging subscribers to this area: @dotnet/area-system-memory See info in area-owners.md if you want to be subscribed.