Created
September 5, 2012 21:54
-
-
Save Buildstarted/3645651 to your computer and use it in GitHub Desktop.
IEnumerable wrapper that allows for peeking
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 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