Last active
May 26, 2020 08:56
-
-
Save MihaZupan/556a8a0a0da6d17fe7a03bc5e4137fae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed unsafe class SpanToMemoryMemoryManager<T> : MemoryManager<T> where T : unmanaged | |
{ | |
[MethodImpl(MethodImplOptions.AggressiveInlining)] | |
public static Memory<T> GetMemory(Span<T> span) | |
{ | |
return new SpanToMemoryMemoryManager<T>(span).Memory; | |
} | |
private readonly T* _ptr; | |
private readonly int _length; | |
public SpanToMemoryMemoryManager(Span<T> span) | |
{ | |
_ptr = (T*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)); | |
_length = span.Length; | |
} | |
public override Span<T> GetSpan() => new Span<T>(_ptr, _length); | |
public override Memory<T> Memory => CreateMemory(_length); | |
public override MemoryHandle Pin(int elementIndex = 0) | |
{ | |
if ((uint)elementIndex < (uint)_length) | |
return new MemoryHandle(_ptr + elementIndex); | |
throw new ArgumentOutOfRangeException(nameof(elementIndex)); | |
} | |
public override void Unpin() { } | |
protected override void Dispose(bool disposing) { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment