PkmnLibSharp/PkmnLibSharp/Utilities/NativePtrArray.cs

111 lines
2.8 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
namespace PkmnLibSharp.Utilities
{
public class NativePtrArray<T> : IList<T> where T : PointerWrapper, new()
{
private readonly IntPtr _ptr;
internal NativePtrArray(IntPtr ptr, int length)
{
_ptr = ptr;
Count = length;
}
public IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < Count; i++)
{
yield return this[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
foreach (var v in this)
{
if (item == null)
{
if (v.Ptr == IntPtr.Zero)
return true;
continue;
}
if (item.Ptr == v.Ptr)
return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
public int Count { get; }
public bool IsReadOnly => true;
public int IndexOf(T item)
{
for (var i = 0; i < Count; i++)
{
var p = _ptr + (i * IntPtr.Size);
if (item == null)
return i;
if (p == item.Ptr)
return i;
}
return -1;
}
public void Insert(int index, T item)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public T this[int index]
{
get
{
unsafe
{
// 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.)
var p = new IntPtr(*(void**)IntPtr.Add(_ptr, index * IntPtr.Size).ToPointer());
if (PointerWrapper.TryResolvePointer(p, out T t))
return t;
t = new T();
t.Initialize(p);
return t;
}
}
set => throw new NotImplementedException();
}
}
}