Line data Source code
1 : // Copyright (c) 2017, 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 : import 'dart:collection'; 6 : 7 : import 'combined_iterator.dart'; 8 : 9 : /// A view of several lists combined into a single list. 10 : /// 11 : /// All methods and accessors treat the [CombinedListView] list as if it were a 12 : /// single concatenated list, but the underlying implementation is based on 13 : /// lazily accessing individual list instances. This means that if the 14 : /// underlying lists change, the [CombinedListView] will reflect those changes. 15 : /// 16 : /// The index operator (`[]`) and [length] property of a [CombinedListView] are 17 : /// both `O(lists)` rather than `O(1)`. A [CombinedListView] is unmodifiable. 18 : class CombinedListView<T> extends ListBase<T> 19 : implements UnmodifiableListView<T> { 20 0 : static Never _throw() { 21 0 : throw UnsupportedError('Cannot modify an unmodifiable List'); 22 : } 23 : 24 : /// The lists that this combines. 25 : final List<List<T>> _lists; 26 : 27 : /// Creates a combined view of [lists]. 28 0 : CombinedListView(this._lists); 29 : 30 0 : @override 31 : Iterator<T> get iterator => 32 0 : CombinedIterator<T>(_lists.map((i) => i.iterator).iterator); 33 : 34 0 : @override 35 : set length(int length) { 36 0 : _throw(); 37 : } 38 : 39 0 : @override 40 0 : int get length => _lists.fold(0, (length, list) => length + list.length); 41 : 42 0 : @override 43 : T operator [](int index) { 44 : var initialIndex = index; 45 0 : for (var i = 0; i < _lists.length; i++) { 46 0 : var list = _lists[i]; 47 0 : if (index < list.length) { 48 0 : return list[index]; 49 : } 50 0 : index -= list.length; 51 : } 52 0 : throw RangeError.index(initialIndex, this, 'index', null, length); 53 : } 54 : 55 0 : @override 56 : void operator []=(int index, T value) { 57 0 : _throw(); 58 : } 59 : 60 0 : @override 61 : void clear() { 62 0 : _throw(); 63 : } 64 : 65 0 : @override 66 : bool remove(Object? element) { 67 0 : _throw(); 68 : } 69 : 70 0 : @override 71 : void removeWhere(bool Function(T) test) { 72 0 : _throw(); 73 : } 74 : 75 0 : @override 76 : void retainWhere(bool Function(T) test) { 77 0 : _throw(); 78 : } 79 : }