Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Created February 10, 2020 16:43
Show Gist options
  • Save JKamsker/e381b60587c04a0b65d01dfa00aee632 to your computer and use it in GitHub Desktop.
Save JKamsker/e381b60587c04a0b65d01dfa00aee632 to your computer and use it in GitHub Desktop.
FragmentedArray
public class FragmentedArray<T> : IEnumerable<T>
{
private T[][] _fragments;
private int _fragmentSize;
public int Size { get; }
public FragmentedArray(int size, int chunks = 3)
{
Size = size;
_fragmentSize = size / chunks;
_fragments = new T[chunks][];
for (int i = 0; i < chunks; i++)
{
_fragments[i] = ArrayPool<T>.Shared.Rent(_fragmentSize);
}
}
public T this[int index] // Indexer declaration
{
//Will be round down, this is pretty handy
get => _fragments[index / _fragmentSize][index % _fragmentSize];
//Will be round down, this is pretty handy
set => _fragments[index / _fragmentSize][index % _fragmentSize] = value;
}
public IEnumerable<T> AsEnumerable()
{
for (int i = 0; i < Size; i++)
{
yield return this[i];
}
}
public IEnumerator<T> GetEnumerator()
{
return AsEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment