Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Created September 5, 2012 21:54
Show Gist options
  • Select an option

  • Save Buildstarted/3645651 to your computer and use it in GitHub Desktop.

Select an option

Save Buildstarted/3645651 to your computer and use it in GitHub Desktop.
IEnumerable wrapper that allows for peeking
public class Stream<T>
{
private IEnumerable<T> _source;
private Queue<T> _storage;
private IEnumerator<T> _enumerator;
public Stream(IEnumerable<T> source)
{
_storage = new Queue<T>();
_source = source;
_enumerator = source.GetEnumerator();
}
public T Peek()
{
if (!_storage.Any())
{
try
{
_storage.Enqueue(GetNext());
}
catch (Exception)
{
return default(T);
}
}
return _storage.Peek();
}
public T Next()
{
if (_storage.Any())
{
return _storage.Dequeue();
}
return GetNext();
}
private T GetNext()
{
//should i consume whitespace here?
while (_enumerator.MoveNext())
{
if ((_enumerator.Current as Token).Type != TokenType.Whitespace)
{
return _enumerator.Current;
}
}
throw new Exception("End of line");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment