//
// NostaleList.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using Reloaded.Memory.Pointers;
using Reloaded.Memory.Sources;
namespace NosSmooth.LocalBinding.Structs;
///
/// A class representing a list from nostale.
///
/// The type.
public class NostaleList : IEnumerable
where T : NostaleObject, new()
{
private readonly IMemory _memory;
///
/// Initializes a new instance of the class.
///
/// The memory.
/// The object list pointer.
public NostaleList(IMemory memory, IntPtr objListPointer)
{
_memory = memory;
Address = objListPointer;
}
///
/// Gets the address.
///
protected IntPtr Address { get; }
///
/// Gets the element at the given index.
///
/// The index of the element.
/// Thrown if the index is not in the bounds of the array.
public T this[int index]
{
get
{
if (index >= Length || index < 0)
{
throw new IndexOutOfRangeException();
}
_memory.SafeRead(Address + 0x04, out int arrayAddress);
_memory.SafeRead((IntPtr)arrayAddress + (0x04 * index), out int objectAddress);
return new T
{
Memory = _memory,
Address = (IntPtr)objectAddress
};
}
}
///
/// Gets the length of the array.
///
public int Length
{
get
{
_memory.SafeRead(Address + 0x08, out int length);
return length;
}
}
///
public IEnumerator GetEnumerator()
{
return new NostaleListEnumerator(this);
}
///
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class NostaleListEnumerator : IEnumerator
{
private readonly NostaleList _list;
private int _index;
public NostaleListEnumerator(NostaleList list)
{
_index = -1;
_list = list;
}
public bool MoveNext()
{
if (_list.Length > _index + 1)
{
_index++;
return true;
}
return false;
}
public void Reset()
{
_index = -1;
}
public T Current => _list[_index];
object IEnumerator.Current => Current;
public void Dispose()
{
}
}
}