Skip to content

Instantly share code, notes, and snippets.

@musoftware
Created August 16, 2017 17:32
Show Gist options
  • Save musoftware/6373f219e4fbfd9f68bb7ae18e1554ff to your computer and use it in GitHub Desktop.
Save musoftware/6373f219e4fbfd9f68bb7ae18e1554ff to your computer and use it in GitHub Desktop.
C# Big Array Class One Dimensional Array Greater than 2Gb.
[Serializable]
public class BigArray<T> : IEnumerable<T>
{
private readonly T[][] _arrays;
public ulong Length { get; private set;}
public T this[ulong index]
{
get
{
if (index > Length - 1)
throw new Exception("Getter: Index out of bound "+index+" must be less than or equal to "+(Length - 1));
return _arrays[index >> 19][index & 524287UL];
}
set
{
if (index > Length - 1)
throw new Exception("Setter: Index out of bound "+index+" must be less than or equal to "+(Length - 1));
_arrays[index >> 19][index & 524287UL] = value;
}
}
public BigArray(ulong size)
{
var NumberOfArrays = size / 524288UL;
while (NumberOfArrays * 524288UL < size)
++NumberOfArrays;
Length = NumberOfArrays * 524288UL;
_arrays = new T[NumberOfArrays][];
for (ulong i = 0; i < NumberOfArrays; ++i)
_arrays[i] = new T[524288];
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
[Serializable]
public struct Enumerator : IEnumerator<T>
{
private readonly BigArray<T> biga;
private ulong index;
public T Current { get; private set; }
object IEnumerator.Current
{
get
{
if (index == biga.Length + 1)
throw new InvalidOperationException("Enumerator out of range: " + index);
return Current;
}
}
internal Enumerator(BigArray<T> biga)
{
this.biga = biga;
index = 0;
Current = default(T);
}
public void Dispose()
{
}
public bool MoveNext()
{
if (index < biga.Length)
{
Current = biga[index];
index++;
return true;
}
index = biga.Length + 1;
Current = default(T);
return false;
}
void IEnumerator.Reset()
{
index = 0;
Current = default(T);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment