Skip to content

Instantly share code, notes, and snippets.

@ElysiumWhale
Created March 26, 2021 06:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElysiumWhale/01e6145b25329c77378876d870e3994b to your computer and use it in GitHub Desktop.
Save ElysiumWhale/01e6145b25329c77378876d870e3994b to your computer and use it in GitHub Desktop.
Stack-like working collection class which drops bottom value while adding new value if store is full
public class LimitedSizeStack<T>
{
private int _count;
private int _index;
private int _limit;
private T[] _data;
public int Count => _count;
public int Limit => _limit;
public LimitedSizeStack(int limit)
{
#warning Zero size stack danger!
if (limit <= 0) _limit = -1;
// or there can be
// throw new ArgumentException("Size of stack can't be 0 or less");
else
{
_count = 0;
_limit = limit;
_data = new T[limit];
_index = 0;
}
}
private void IncreaseIndex() => _index = (_index == _limit - 1) ? 0 : _index + 1;
public void Push(T item)
{
if (_limit == -1) return;
if (_count != _limit)
{
_data[_index] = item;
_count++;
IncreaseIndex();
}
else if (_count == _limit)
{
_data[_index] = item;
IncreaseIndex();
}
}
public T Pop()
{
if (_limit == -1) return default;
if (_count == 0) return default;
_index = (_index == 0) ? (_limit - 1) : _index - 1;
T res = _data[_index];
_data[_index] = default;
_count--;
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment