OLD | NEW |
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 part of dart.collection; | 5 part of dart.collection; |
6 | 6 |
7 /** | 7 /** |
8 * The [HasNextIterator] class wraps an [Iterator] and provides methods to | 8 * The [HasNextIterator] class wraps an [Iterator] and provides methods to |
9 * iterate over an object using `hasNext` and `next`. | 9 * iterate over an object using `hasNext` and `next`. |
10 * | 10 * |
11 * An [HasNextIterator] does not implement the [Iterator] interface. | 11 * An [HasNextIterator] does not implement the [Iterator] interface. |
12 */ | 12 */ |
13 class HasNextIterator<E> { | 13 class HasNextIterator<E> { |
14 static const int _HAS_NEXT_AND_NEXT_IN_CURRENT = 0; | 14 static const int _HAS_NEXT_AND_NEXT_IN_CURRENT = 0; |
15 static const int _NO_NEXT = 1; | 15 static const int _NO_NEXT = 1; |
16 static const int _NOT_MOVED_YET = 2; | 16 static const int _NOT_MOVED_YET = 2; |
17 | 17 |
18 Iterator _iterator; | 18 Iterator<E> _iterator; |
19 int _state = _NOT_MOVED_YET; | 19 int _state = _NOT_MOVED_YET; |
20 | 20 |
21 HasNextIterator(this._iterator); | 21 HasNextIterator(this._iterator); |
22 | 22 |
23 bool get hasNext { | 23 bool get hasNext { |
24 if (_state == _NOT_MOVED_YET) _move(); | 24 if (_state == _NOT_MOVED_YET) _move(); |
25 return _state == _HAS_NEXT_AND_NEXT_IN_CURRENT; | 25 return _state == _HAS_NEXT_AND_NEXT_IN_CURRENT; |
26 } | 26 } |
27 | 27 |
28 E next() { | 28 E next() { |
29 // Call to hasNext is necessary to make sure we are positioned at the first | 29 // Call to hasNext is necessary to make sure we are positioned at the first |
30 // element when we start iterating. | 30 // element when we start iterating. |
31 if (!hasNext) throw new StateError("No more elements"); | 31 if (!hasNext) throw new StateError("No more elements"); |
32 assert(_state == _HAS_NEXT_AND_NEXT_IN_CURRENT); | 32 assert(_state == _HAS_NEXT_AND_NEXT_IN_CURRENT); |
33 E result = _iterator.current; | 33 E result = _iterator.current; |
34 _move(); | 34 _move(); |
35 return result; | 35 return result; |
36 } | 36 } |
37 | 37 |
38 void _move() { | 38 void _move() { |
39 if (_iterator.moveNext()) { | 39 if (_iterator.moveNext()) { |
40 _state = _HAS_NEXT_AND_NEXT_IN_CURRENT; | 40 _state = _HAS_NEXT_AND_NEXT_IN_CURRENT; |
41 } else { | 41 } else { |
42 _state = _NO_NEXT; | 42 _state = _NO_NEXT; |
43 } | 43 } |
44 } | 44 } |
45 } | 45 } |
OLD | NEW |