Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1291)

Unified Diff: sdk/lib/core/iterator.dart

Issue 11410086: Use iterator, moveNext(), current. (Closed) Base URL: https://dart.googlecode.com/svn/experimental/lib_v2/dart
Patch Set: Address comments. Created 8 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: sdk/lib/core/iterator.dart
diff --git a/sdk/lib/core/iterator.dart b/sdk/lib/core/iterator.dart
index 5d5e979687f5db87c675484c2177bbdb861ca15f..7f7f63087a992e00e79ff73f8af84e46f881275b 100644
--- a/sdk/lib/core/iterator.dart
+++ b/sdk/lib/core/iterator.dart
@@ -9,16 +9,63 @@
*
* If the object iterated over is changed during the iteration, the
* behavior is unspecified.
+ *
+ * The [Iterator] is initially positioned before the first element. Before
+ * accessing the first element the iterator must thus be advanced ([moveNext])
+ * to point to the first element. If there is no element left, then [moveNext]
+ * returns false.
*/
abstract class Iterator<E> {
/**
- * Gets the next element in the iteration. Throws a
- * [StateError] if no element is left.
+ * Moves to the next element. Returns true if [current] contains the next
+ * element. Returns false, if no element was left. It the latter case
+ * trying to read [current] will throw a [StateError].
+ *
+ * It is safe to invoke [moveNext] even when the iterator is already
+ * positioned after the last element. In this case [moveNext] has no effect.
*/
- E next();
+ bool moveNext();
/**
- * Returns whether the [Iterator] has elements left.
+ * Returns the current element.
+ *
+ * Throws a [StateError] if the iterator has not yet been moved to the first
+ * element, or if the iterator has been moved after the last element of the
+ * [Iterable].
*/
- bool get hasNext;
+ E get current;
+}
+
+class HasNextIterator<E> {
+ static const int _HAS_NEXT_AND_NEXT_IN_CURRENT = 0;
+ static const int _NO_NEXT = 1;
+ static const int _NOT_MOVED_YET = 2;
+
+ Iterator _iterator;
+ int _state = _NOT_MOVED_YET;
+
+ HasNextIterator(this._iterator);
+
+ bool get hasNext {
+ switch(_state) {
+ case _NOT_MOVED_YET:
+ bool currentIsValid = _iterator.moveNext();
+ if (currentIsValid) {
+ _state = _HAS_NEXT_AND_NEXT_IN_CURRENT;
+ } else {
+ _state = _NO_NEXT;
+ }
+ return currentIsValid;
+ case _HAS_NEXT_AND_NEXT_IN_CURRENT:
+ return true;
+ case _NO_NEXT:
+ return false;
+ }
+ }
+
+ E next() {
+ if (!hasNext) throw new StateError("No more elements");
+ assert(_state == _HAS_NEXT_AND_NEXT_IN_CURRENT);
+ return _iterator.current;
+ }
}

Powered by Google App Engine
This is Rietveld 408576698