PkmnLibRSharp/PkmnLibRSharp/Utils/CachedExternArray.cs

77 lines
1.9 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace PkmnLibSharp.Utils
{
public class CachedExternArray<T> : IReadOnlyList<T>
where T: class
{
private readonly T?[] _array;
private readonly Func<ulong, T> _getItem;
public CachedExternArray(ulong size, Func<ulong, T> getItem)
{
_array = new T?[(int)size];
_getItem = getItem;
}
public IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < Count; i++)
{
yield return this[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Count => _array.Length;
public T this[int index]
{
get
{
if (index >= _array.Length)
throw new ArgumentOutOfRangeException(
$"Index {index} was outside of the bounds of the external array with length {Count}");
return _array[index] ??= _getItem((ulong)index);
}
}
}
public class CachedExternValueArray<T> : IReadOnlyList<T>
where T: struct
{
private readonly T?[] _array;
private readonly Func<ulong, T> _getItem;
public CachedExternValueArray(ulong size, Func<ulong, T> getItem)
{
_array = new T?[(int)size];
_getItem = getItem;
}
public IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < Count; i++)
{
yield return this[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Count => _array.Length;
public T this[int index] => _array[index] ??= _getItem((ulong)index);
}
}