Lock cache while using it in ReadOnlyNativeArray

This commit is contained in:
Deukhoofd 2021-01-16 19:50:43 +01:00
parent d5bbc18b1a
commit d38338ddc3
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 20 additions and 19 deletions

View File

@ -71,38 +71,39 @@ namespace PkmnLibSharp.Utilities
return -1; return -1;
} }
internal T? GetDontInitialise(int index) private unsafe IntPtr GetPtr(int index)
{
unsafe
{ {
if (index >= Count) if (index >= Count)
throw new IndexOutOfRangeException(); throw new IndexOutOfRangeException();
// Where's your god now? // Where's your god now?
// (We add the offset of the index to the pointer, then dereference the pointer pointer to get the actual pointer to the object we want.) // (We add the offset of the index to the pointer, then dereference the pointer pointer to get the actual pointer to the object we want.)
var p = new IntPtr(*(void**)IntPtr.Add(_ptr, index * IntPtr.Size).ToPointer()); return new IntPtr(*(void**)IntPtr.Add(_ptr, index * IntPtr.Size).ToPointer());
}
internal T? GetDontInitialise(int index)
{
var p = GetPtr(index);
if (p == IntPtr.Zero) if (p == IntPtr.Zero)
return null; return null;
lock (_cache)
{
if (_cache[index]?.Ptr == p) if (_cache[index]?.Ptr == p)
return _cache[index]!; return _cache[index]!;
}
if (PointerWrapper.TryResolvePointer(p, out T? t)) if (PointerWrapper.TryResolvePointer(p, out T? t))
return t!; return t!;
return null; return null;
} }
}
public T? this[int index] public T? this[int index]
{ {
get get
{ {
unsafe var p = GetPtr(index);
{
if (index >= Count)
throw new IndexOutOfRangeException();
// Where's your god now?
// (We add the offset of the index to the pointer, then dereference the pointer pointer to get the actual pointer to the object we want.)
var p = new IntPtr(*(void**)IntPtr.Add(_ptr, index * IntPtr.Size).ToPointer());
if (p == IntPtr.Zero) if (p == IntPtr.Zero)
return null; return null;
lock (_cache)
{
if (_cache[index]?.Ptr == p) if (_cache[index]?.Ptr == p)
return _cache[index]!; return _cache[index]!;
if (PointerWrapper.TryResolvePointer(p, out T? t)) if (PointerWrapper.TryResolvePointer(p, out T? t))