aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Graphics.Vulkan/NativeArray.cs
blob: f74074390a76af0021f41ad4c635b917e9369c71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryujinx.Graphics.Vulkan
{
    unsafe class NativeArray<T> : IDisposable where T : unmanaged
    {
        public T* Pointer { get; private set; }
        public int Length { get; }

        public ref T this[int index]
        {
            get => ref Pointer[Checked(index)];
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private int Checked(int index)
        {
            if ((uint)index >= (uint)Length)
            {
                throw new IndexOutOfRangeException();
            }

            return index;
        }

        public NativeArray(int length)
        {
            Pointer = (T*)Marshal.AllocHGlobal(checked(length * Unsafe.SizeOf<T>()));
            Length = length;
        }

        public Span<T> AsSpan()
        {
            return new Span<T>(Pointer, Length);
        }

        public void Dispose()
        {
            Marshal.FreeHGlobal((IntPtr)Pointer);
            Pointer = null;
        }
    }
}