public override unsafe MemoryHandle Pin(int offset = 0)
{
- if (offset < 0 || offset >= _length) throw new ArgumentOutOfRangeException(nameof(offset));
+ if (offset < 0 || (_length > 0 && offset >= _length)) throw new ArgumentOutOfRangeException(nameof(offset));
void* pointer = (void*)((byte*)_ptr + offset);
return new MemoryHandle(this, pointer);
}
unsafe
{
Retain();
- if (offset < 0 || offset >= _array.Length) throw new ArgumentOutOfRangeException(nameof(offset));
+ if (offset < 0 || (_array.Length > 0 && offset >= _array.Length)) throw new ArgumentOutOfRangeException(nameof(offset));
var handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
return new MemoryHandle(this, Unsafe.Add<byte>((void*)handle.AddrOfPinnedObject(), offset), handle);
}
owner.Dispose();
Assert.True(owner.IsDisposed);
}
+
+ [Fact]
+ public static void OwnedMemoryPinEmptyArray()
+ {
+ int[] a = {};
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ MemoryHandle handle = owner.Pin();
+ Assert.True(handle.HasPointer);
+ }
+
+ [Fact]
+ public static void OwnedMemoryPinArray()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ MemoryHandle handle = owner.Pin();
+ Assert.True(handle.HasPointer);
+ unsafe
+ {
+ int* pointer = (int*)handle.Pointer;
+
+ GC.Collect();
+
+ for (int i = 0; i < owner.Memory.Length; i++)
+ {
+ Assert.Equal(array[i], pointer[i]);
+ }
+ }
+ handle.Dispose();
+ }
[Fact]
public static void MemoryFromOwnedMemoryAfterDispose()
}
[Fact]
+ public static void MemoryFromEmptyArrayRetainWithPinning()
+ {
+ Memory<int> memory = new int[0];
+ MemoryHandle handle = memory.Retain(pin: true);
+ Assert.True(handle.HasPointer);
+ unsafe
+ {
+ int* pointer = (int*)handle.Pointer;
+
+ GC.Collect();
+
+ Assert.True(pointer != null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
public static void OwnedMemoryRetainWithPinningAndSlice()
{
int[] array = { 1, 2, 3, 4, 5 };
}
[Fact]
+ public static void MemoryFromEmptyArrayRetainWithPinning()
+ {
+ ReadOnlyMemory<int> memory = new int[0];
+ MemoryHandle handle = memory.Retain(pin: true);
+ Assert.True(handle.HasPointer);
+ unsafe
+ {
+ int* pointer = (int*)handle.Pointer;
+
+ GC.Collect();
+
+ Assert.True(pointer != null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
public static void MemoryRetainWithPinningAndSlice()
{
int[] array = { 1, 2, 3, 4, 5 };