OLD | NEW |
| (Empty) |
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 | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library utf.list_range; | |
6 | |
7 import 'dart:collection'; | |
8 | |
9 /** | |
10 * _ListRange in an internal type used to create a lightweight Interable on a | |
11 * range within a source list. DO NOT MODIFY the underlying list while | |
12 * iterating over it. The results of doing so are undefined. | |
13 */ | |
14 // TODO(floitsch): Consider removing the extend and switch to implements since | |
15 // that's cheaper to allocate. | |
16 class ListRange extends IterableBase { | |
17 final List _source; | |
18 final int _offset; | |
19 final int _length; | |
20 | |
21 ListRange(source, [offset = 0, length]) : | |
22 this._source = source, | |
23 this._offset = offset, | |
24 this._length = (length == null ? source.length - offset : length) { | |
25 if (_offset < 0 || _offset > _source.length) { | |
26 throw new RangeError.value(_offset); | |
27 } | |
28 if (_length != null && (_length < 0)) { | |
29 throw new RangeError.value(_length); | |
30 } | |
31 if (_length + _offset > _source.length) { | |
32 throw new RangeError.value(_length + _offset); | |
33 } | |
34 } | |
35 | |
36 ListRangeIterator get iterator => | |
37 new _ListRangeIteratorImpl(_source, _offset, _offset + _length); | |
38 | |
39 int get length => _length; | |
40 } | |
41 | |
42 /** | |
43 * The ListRangeIterator provides more capabilities than a standard iterator, | |
44 * including the ability to get the current position, count remaining items, | |
45 * and move forward/backward within the iterator. | |
46 */ | |
47 abstract class ListRangeIterator implements Iterator<int> { | |
48 bool moveNext(); | |
49 int get current; | |
50 int get position; | |
51 void backup([int by]); | |
52 int get remaining; | |
53 void skip([int count]); | |
54 } | |
55 | |
56 class _ListRangeIteratorImpl implements ListRangeIterator { | |
57 final List<int> _source; | |
58 int _offset; | |
59 final int _end; | |
60 | |
61 _ListRangeIteratorImpl(this._source, int offset, this._end) | |
62 : _offset = offset - 1; | |
63 | |
64 int get current => _source[_offset]; | |
65 | |
66 bool moveNext() => ++_offset < _end; | |
67 | |
68 int get position => _offset; | |
69 | |
70 void backup([int by = 1]) { | |
71 _offset -= by; | |
72 } | |
73 | |
74 int get remaining => _end - _offset - 1; | |
75 | |
76 void skip([int count = 1]) { | |
77 _offset += count; | |
78 } | |
79 } | |
OLD | NEW |