aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.Core/OsHle/Utilities/IdPoolWithObj.cs
blob: f0a339df3ade085f6ea9bcb7188898e093393c5d (plain)
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
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Ryujinx.Core.OsHle.Utilities
{
    class IdPoolWithObj : IEnumerable<KeyValuePair<int, object>>
    {
        private IdPool Ids;

        private ConcurrentDictionary<int, object> Objs;

        public IdPoolWithObj()
        {
            Ids = new IdPool();

            Objs = new ConcurrentDictionary<int, object>();
        }

        public int GenerateId(object Data)
        {
            int Id = Ids.GenerateId();

            if (Id == -1 || !Objs.TryAdd(Id, Data))
            {
                throw new InvalidOperationException();
            }

            return Id;
        }

        public bool ReplaceData(int Id, object Data)
        {
            if (Objs.ContainsKey(Id))
            {
                Objs[Id] = Data;

                return true;
            }

            return false;
        }

        public T GetData<T>(int Id)
        {
            if (Objs.TryGetValue(Id, out object Data) && Data is T)
            {
                return (T)Data;
            }

            return default(T);
        }

        public void Delete(int Id)
        {
            if (Objs.TryRemove(Id, out object Obj))
            {
                if (Obj is IDisposable DisposableObj)
                {
                    DisposableObj.Dispose();
                }

                Ids.DeleteId(Id);
            }
        }

        IEnumerator<KeyValuePair<int, object>> IEnumerable<KeyValuePair<int, object>>.GetEnumerator()
        {
            return Objs.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return Objs.GetEnumerator();
        }
    }
}