forked from loongly/PureScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectStore.cs
More file actions
117 lines (97 loc) · 2.74 KB
/
Copy pathObjectStore.cs
File metadata and controls
117 lines (97 loc) · 2.74 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
//#define WRAPPER_SIDE
using AOT;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
internal static class ObjectStore
{
// Lookup handles by object.
static Dictionary<object, int> objectHandleCache;
// Stored objects. The first is never used so 0 can be "null".
static object[] objects;
private static Handler handler;
static ObjectStore()
{
Init(1 << 16);
}
public static void Init(int maxObjects)
{
ref Handler h = ref Custom.GetHandler((int)HandlerType.Object);
h.InitHandle(maxObjects);
handler = h;
objectHandleCache = new Dictionary<object, int>(maxObjects, new RObjComparer());
// Initialize the objects as all null plus room for the
// first to always be null.
objects = new object[maxObjects + 1];
}
public static int Store(object obj, int target = 0)
{
// Null is always zero
if (object.ReferenceEquals(obj, null))
{
return 0;
}
lock (objects)
{
if (target == 0)
{
// Get handle from object cache
var h = GetHandle(obj);
if (h > 0)
return h;
target = handler.GrabHandle();
}
// Store the object
StoreInternal(target, obj);
return target;
}
}
private static void StoreInternal(int handle, object obj)
{
objects[handle] = obj;
objectHandleCache.Add(obj, handle);
}
public static int GetHandle(object obj)
{
if (objectHandleCache.TryGetValue(obj, out var handle))
return handle;
return 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object Get(int handle)
{
return objects[handle];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Get<T>(int handle)
{
return (T)Get(handle);
}
[MonoPInvokeCallback(typeof(Custom.RemoveHandleType))]
internal static int OnRemove(int handle)
{
lock (objects)
{
// Forget the object
object obj = objects[handle];
objects[handle] = null;
// Remove the object from the cache
objectHandleCache.Remove(obj);
}
return 0;
}
internal class RObjComparer : IEqualityComparer<object>
{
public bool Equals(object x, object y)
{
return RuntimeHelpers.ReferenceEquals(x, y);
}
public int GetHashCode(object obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
}
}