diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs index 9156b5efd21f4d..d0e7578a5b2db0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryAccessor.cs @@ -358,6 +358,43 @@ public int ReadArray(long position, T[] array, int offset, int count) where T return n; } + public int Read(long position, Span buffer) + { + if (!_isOpen) + { + throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); + } + if (!_canRead) + { + throw new NotSupportedException(SR.NotSupported_Reading); + } + ArgumentOutOfRangeException.ThrowIfNegative(position); + + if (position >= _capacity) + { + throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); + } + + int n = buffer.Length; + long spaceLeft = _capacity - position; + if (spaceLeft < 0) + { + n = 0; + } + else + { + ulong spaceNeeded = (ulong)(n); + if ((ulong)spaceLeft < spaceNeeded) + { + n = (int)(spaceLeft); + } + } + + _buffer.ReadSpan((ulong)(_offset + position), buffer.Slice(0, n)); + + return n; + } + // ************** Write Methods ****************/ public void Write(long position, bool value) => Write(position, (byte)(value ? 1 : 0)); @@ -564,6 +601,26 @@ public void WriteArray(long position, T[] array, int offset, int count) where _buffer.WriteArray((ulong)(_offset + position), array, offset, count); } + public void Write(long position, ReadOnlySpan buffer) + { + ArgumentOutOfRangeException.ThrowIfNegative(position); + if (position >= Capacity) + { + throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired); + } + + if (!_isOpen) + { + throw new ObjectDisposedException(nameof(UnmanagedMemoryAccessor), SR.ObjectDisposed_ViewAccessorClosed); + } + if (!_canWrite) + { + throw new NotSupportedException(SR.NotSupported_Writing); + } + + _buffer.WriteSpan((ulong)(_offset + position), buffer); + } + private void EnsureSafeToRead(long position, int sizeOfType) { if (!_isOpen)