Created
April 26, 2020 05:28
-
-
Save aschuhardt/1889d8f5a03569153a686d877ac16290 to your computer and use it in GitHub Desktop.
A resizable buffer object that exposes its underlying array. This is handy for buffering vertex data directly from where it's stored in memory (i.e. without the additional copy operation that calling List<T>.ToArray() implies).
This file contains 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
/// <summary> | |
/// A resizable buffer object with its underlying array exposed | |
/// </summary> | |
public class ElasticBuffer<T> : ICollection<T> | |
{ | |
private int _capacity = 1, _count = 0; | |
private T[] _buffer; | |
public ElasticBuffer() | |
{ | |
_buffer = new T[_capacity]; | |
} | |
public T[] Buffer => _buffer; | |
public int Count => _count; | |
public bool IsReadOnly => false; | |
public void Add(T item) | |
{ | |
var index = _count++; | |
if (_count > _capacity) | |
{ | |
_capacity *= 2; | |
Array.Resize(ref _buffer, _capacity); | |
} | |
_buffer[index] = item; | |
} | |
public void Clear() | |
{ | |
_count = 0; | |
} | |
public bool Contains(T item) | |
{ | |
for (int i = 0; i < _count; i++) | |
{ | |
if (_buffer[i].Equals(item)) | |
return true; | |
} | |
return false; | |
} | |
public void CopyTo(T[] array, int arrayIndex) | |
{ | |
_buffer.CopyTo(array, arrayIndex); | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
for (int i = 0; i < _count; i++) | |
yield return _buffer[i]; | |
yield break; | |
} | |
public bool Remove(T item) | |
{ | |
for (int i = 0; i < _count; i++) | |
{ | |
if (_buffer[i].Equals(item)) | |
{ | |
Array.Copy(_buffer, i + 1, _buffer, i, (_count-- - i)); | |
return true; | |
} | |
} | |
return false; | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return ((ICollection<T>)this).GetEnumerator(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment