aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Graphics.Vulkan/NativeArray.cs
blob: 7678b63c8e88c7a04a6c1b4764cb499a06239f92 (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
46
47
48
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()
        {
            if (Pointer != null)
            {
                Marshal.FreeHGlobal((IntPtr)Pointer);
                Pointer = null;
            }
        }
    }
}