Created
February 10, 2020 16:43
-
-
Save JKamsker/e381b60587c04a0b65d01dfa00aee632 to your computer and use it in GitHub Desktop.
FragmentedArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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