From d38338ddc30fa255502232010ae57de006b04063 Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Sat, 16 Jan 2021 19:50:43 +0100 Subject: [PATCH] Lock cache while using it in ReadOnlyNativeArray --- .../Utilities/ReadOnlyNativePtrArray.cs | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/PkmnLibSharp/Utilities/ReadOnlyNativePtrArray.cs b/PkmnLibSharp/Utilities/ReadOnlyNativePtrArray.cs index eadb8bc..e245df7 100644 --- a/PkmnLibSharp/Utilities/ReadOnlyNativePtrArray.cs +++ b/PkmnLibSharp/Utilities/ReadOnlyNativePtrArray.cs @@ -71,38 +71,39 @@ namespace PkmnLibSharp.Utilities return -1; } + private unsafe IntPtr GetPtr(int 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.) + return new IntPtr(*(void**)IntPtr.Add(_ptr, index * IntPtr.Size).ToPointer()); + } + internal T? GetDontInitialise(int index) { - unsafe + var p = GetPtr(index); + if (p == IntPtr.Zero) + return null; + lock (_cache) { - 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) - return null; if (_cache[index]?.Ptr == p) return _cache[index]!; - if (PointerWrapper.TryResolvePointer(p, out T? t)) - return t!; - return null; } + if (PointerWrapper.TryResolvePointer(p, out T? t)) + return t!; + return null; } public T? this[int index] { get { - unsafe + var p = GetPtr(index); + if (p == IntPtr.Zero) + return null; + lock (_cache) { - 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) - return null; if (_cache[index]?.Ptr == p) return _cache[index]!; if (PointerWrapper.TryResolvePointer(p, out T? t))