aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Graphics.Nvdec.Vp9/Common/MemoryAllocator.cs
blob: c75cfeb0f0e5aa469eb712c81e814b5a8b28c558 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using Ryujinx.Common.Memory;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Ryujinx.Graphics.Nvdec.Vp9.Common
{
    internal class MemoryAllocator : IDisposable
    {
        private const int PoolEntries = 10;

        private struct PoolItem
        {
            public IntPtr Pointer;
            public int Length;
            public bool InUse;
        }

        private readonly PoolItem[] _pool = new PoolItem[PoolEntries];

        public ArrayPtr<T> Allocate<T>(int length) where T : unmanaged
        {
            int lengthInBytes = Unsafe.SizeOf<T>() * length;

            IntPtr ptr = IntPtr.Zero;

            for (int i = 0; i < PoolEntries; i++)
            {
                ref PoolItem item = ref _pool[i];

                if (!item.InUse && item.Length == lengthInBytes)
                {
                    item.InUse = true;
                    ptr = item.Pointer;
                    break;
                }
            }

            if (ptr == IntPtr.Zero)
            {
                ptr = Marshal.AllocHGlobal(lengthInBytes);

                for (int i = 0; i < PoolEntries; i++)
                {
                    ref PoolItem item = ref _pool[i];

                    if (!item.InUse)
                    {
                        item.InUse = true;
                        if (item.Pointer != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(item.Pointer);
                        }
                        item.Pointer = ptr;
                        item.Length = lengthInBytes;
                        break;
                    }
                }
            }

            return new ArrayPtr<T>(ptr, length);
        }

        public unsafe void Free<T>(ArrayPtr<T> arr) where T : unmanaged
        {
            IntPtr ptr = (IntPtr)arr.ToPointer();

            for (int i = 0; i < PoolEntries; i++)
            {
                ref PoolItem item = ref _pool[i];

                if (item.Pointer == ptr)
                {
                    item.InUse = false;
                    break;
                }
            }
        }

        public void Dispose()
        {
            for (int i = 0; i < PoolEntries; i++)
            {
                ref PoolItem item = ref _pool[i];

                if (item.Pointer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(item.Pointer);
                    item.Pointer = IntPtr.Zero;
                }
            }
        }
    }
}