Fix newly enforced package:pedantic lints (#112)
- always_declare_return_types
- annotate_overrides
- omit_local_variable_types
- prefer_collection_literals
- prefer_conditional_assignment
- prefer_single_quotes
- prefer_spread_collections
- unnecessary_this
- use_function_type_syntax_for_parameters
Bump minimum SDK to 2.3.0 for Set literals and collection spread
elements.
Convert from windows to unix line endings in `comparator.dart`.
diff --git a/.travis.yml b/.travis.yml
index 433c12e..96ba17a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,7 @@
language: dart
dart:
-- 2.0.0
+- 2.3.0
- dev
dart_task:
@@ -15,7 +15,7 @@
- dart: dev
dart_task:
dartanalyzer: --fatal-infos --fatal-warnings .
- - dart: 2.0.0
+ - dart: 2.3.0
dart_task:
dartanalyzer: --fatal-warnings .
diff --git a/lib/algorithms.dart b/lib/algorithms.dart
index 4d3ae8b..df0d712 100644
--- a/lib/algorithms.dart
+++ b/lib/algorithms.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
/// Import `collection.dart` instead.
-@Deprecated("Will be removed in collection 2.0.0.")
+@Deprecated('Will be removed in collection 2.0.0.')
library dart.pkg.collection.algorithms;
-export "src/algorithms.dart";
+export 'src/algorithms.dart';
diff --git a/lib/collection.dart b/lib/collection.dart
index 70f9fbc..282d60f 100644
--- a/lib/collection.dart
+++ b/lib/collection.dart
@@ -2,20 +2,20 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-export "src/algorithms.dart";
-export "src/canonicalized_map.dart";
-export "src/combined_wrappers/combined_iterable.dart";
-export "src/combined_wrappers/combined_list.dart";
-export "src/combined_wrappers/combined_map.dart";
-export "src/comparators.dart";
-export "src/equality.dart";
-export "src/equality_map.dart";
-export "src/equality_set.dart";
-export "src/functions.dart";
-export "src/iterable_zip.dart";
-export "src/priority_queue.dart";
-export "src/queue_list.dart";
-export "src/union_set.dart";
-export "src/union_set_controller.dart";
-export "src/unmodifiable_wrappers.dart";
-export "src/wrappers.dart";
+export 'src/algorithms.dart';
+export 'src/canonicalized_map.dart';
+export 'src/combined_wrappers/combined_iterable.dart';
+export 'src/combined_wrappers/combined_list.dart';
+export 'src/combined_wrappers/combined_map.dart';
+export 'src/comparators.dart';
+export 'src/equality.dart';
+export 'src/equality_map.dart';
+export 'src/equality_set.dart';
+export 'src/functions.dart';
+export 'src/iterable_zip.dart';
+export 'src/priority_queue.dart';
+export 'src/queue_list.dart';
+export 'src/union_set.dart';
+export 'src/union_set_controller.dart';
+export 'src/unmodifiable_wrappers.dart';
+export 'src/wrappers.dart';
diff --git a/lib/equality.dart b/lib/equality.dart
index 0f5b51d..021430b 100644
--- a/lib/equality.dart
+++ b/lib/equality.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
/// Import `collection.dart` instead.
-@Deprecated("Will be removed in collection 2.0.0.")
+@Deprecated('Will be removed in collection 2.0.0.')
library dart.pkg.collection.equality;
-export "src/equality.dart";
+export 'src/equality.dart';
diff --git a/lib/iterable_zip.dart b/lib/iterable_zip.dart
index 34e18ef..1ef5595 100644
--- a/lib/iterable_zip.dart
+++ b/lib/iterable_zip.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
/// Import `collection.dart` instead.
-@Deprecated("Will be removed in collection 2.0.0.")
+@Deprecated('Will be removed in collection 2.0.0.')
library dart.pkg.collection.iterable_zip;
-export "src/iterable_zip.dart";
+export 'src/iterable_zip.dart';
diff --git a/lib/priority_queue.dart b/lib/priority_queue.dart
index f2a4703..9ed8be8 100644
--- a/lib/priority_queue.dart
+++ b/lib/priority_queue.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
/// Import `collection.dart` instead.
-@Deprecated("Will be removed in collection 2.0.0.")
+@Deprecated('Will be removed in collection 2.0.0.')
library dart.pkg.collection.priority_queue;
-export "src/priority_queue.dart";
+export 'src/priority_queue.dart';
diff --git a/lib/src/algorithms.dart b/lib/src/algorithms.dart
index 9a9e371..9722b77 100644
--- a/lib/src/algorithms.dart
+++ b/lib/src/algorithms.dart
@@ -2,9 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:math" as math;
+import 'dart:math' as math;
-import "utils.dart";
+import 'utils.dart';
/// Returns a position of the [value] in [sortedList], if it is there.
///
@@ -15,14 +15,14 @@
/// the objects. If any object is not [Comparable], this throws a [CastError].
///
/// Returns -1 if [value] is not in the list by default.
-int binarySearch<T>(List<T> sortedList, T value, {int compare(T a, T b)}) {
+int binarySearch<T>(List<T> sortedList, T value, {int Function(T, T) compare}) {
compare ??= defaultCompare<T>();
- int min = 0;
- int max = sortedList.length;
+ var min = 0;
+ var max = sortedList.length;
while (min < max) {
- int mid = min + ((max - min) >> 1);
+ var mid = min + ((max - min) >> 1);
var element = sortedList[mid];
- int comp = compare(element, value);
+ var comp = compare(element, value);
if (comp == 0) return mid;
if (comp < 0) {
min = mid + 1;
@@ -44,14 +44,14 @@
///
/// Returns [sortedList.length] if all the items in [sortedList] compare less
/// than [value].
-int lowerBound<T>(List<T> sortedList, T value, {int compare(T a, T b)}) {
+int lowerBound<T>(List<T> sortedList, T value, {int Function(T, T) compare}) {
compare ??= defaultCompare<T>();
- int min = 0;
- int max = sortedList.length;
+ var min = 0;
+ var max = sortedList.length;
while (min < max) {
- int mid = min + ((max - min) >> 1);
+ var mid = min + ((max - min) >> 1);
var element = sortedList[mid];
- int comp = compare(element, value);
+ var comp = compare(element, value);
if (comp < 0) {
min = mid + 1;
} else {
@@ -66,10 +66,10 @@
/// A sub-range of a list can be shuffled by providing [start] and [end].
void shuffle(List list, [int start = 0, int end]) {
var random = math.Random();
- if (end == null) end = list.length;
- int length = end - start;
+ end ??= list.length;
+ var length = end - start;
while (length > 1) {
- int pos = random.nextInt(length);
+ var pos = random.nextInt(length);
length--;
var tmp1 = list[start + pos];
list[start + pos] = list[start + length];
@@ -79,13 +79,13 @@
/// Reverses a list, or a part of a list, in-place.
void reverse(List list, [int start = 0, int end]) {
- if (end == null) end = list.length;
+ end ??= list.length;
_reverse(list, start, end);
}
/// Internal helper function that assumes valid arguments.
void _reverse(List list, int start, int end) {
- for (int i = start, j = end - 1; i < j; i++, j--) {
+ for (var i = start, j = end - 1; i < j; i++, j--) {
var tmp = list[i];
list[i] = list[j];
list[j] = tmp;
@@ -108,19 +108,19 @@
/// This insertion sort is stable: Equal elements end up in the same order
/// as they started in.
void insertionSort<T>(List<T> list,
- {int compare(T a, T b), int start = 0, int end}) {
+ {int Function(T, T) compare, int start = 0, int end}) {
// If the same method could have both positional and named optional
// parameters, this should be (list, [start, end], {compare}).
compare ??= defaultCompare<T>();
end ??= list.length;
- for (int pos = start + 1; pos < end; pos++) {
- int min = start;
- int max = pos;
+ for (var pos = start + 1; pos < end; pos++) {
+ var min = start;
+ var max = pos;
var element = list[pos];
while (min < max) {
- int mid = min + ((max - min) >> 1);
- int comparison = compare(element, list[mid]);
+ var mid = min + ((max - min) >> 1);
+ var comparison = compare(element, list[mid]);
if (comparison < 0) {
max = mid;
} else {
@@ -151,11 +151,11 @@
/// This merge sort is stable: Equal elements end up in the same order
/// as they started in.
void mergeSort<T>(List<T> list,
- {int start = 0, int end, int compare(T a, T b)}) {
+ {int start = 0, int end, int Function(T, T) compare}) {
end ??= list.length;
compare ??= defaultCompare<T>();
- int length = end - start;
+ var length = end - start;
if (length < 2) return;
if (length < _MERGE_SORT_LIMIT) {
insertionSort(list, compare: compare, start: start, end: end);
@@ -167,13 +167,13 @@
// of the same size as the list to sort.
// This split allows us to have only half as much extra space,
// and it ends up in the original place.
- int middle = start + ((end - start) >> 1);
- int firstLength = middle - start;
- int secondLength = end - middle;
+ var middle = start + ((end - start) >> 1);
+ var firstLength = middle - start;
+ var secondLength = end - middle;
// secondLength is always the same as firstLength, or one greater.
var scratchSpace = List<T>(secondLength);
_mergeSort(list, compare, middle, end, scratchSpace, 0);
- int firstTarget = end - firstLength;
+ var firstTarget = end - firstLength;
_mergeSort(list, compare, start, middle, list, firstTarget);
_merge(compare, list, firstTarget, end, scratchSpace, 0, secondLength, list,
start);
@@ -183,17 +183,17 @@
/// one containing the original values.
///
/// It will work in-place as well.
-void _movingInsertionSort<T>(List<T> list, int compare(T a, T b), int start,
- int end, List<T> target, int targetOffset) {
- int length = end - start;
+void _movingInsertionSort<T>(List<T> list, int Function(T, T) compare,
+ int start, int end, List<T> target, int targetOffset) {
+ var length = end - start;
if (length == 0) return;
target[targetOffset] = list[start];
- for (int i = 1; i < length; i++) {
+ for (var i = 1; i < length; i++) {
var element = list[start + i];
- int min = targetOffset;
- int max = targetOffset + i;
+ var min = targetOffset;
+ var max = targetOffset + i;
while (min < max) {
- int mid = min + ((max - min) >> 1);
+ var mid = min + ((max - min) >> 1);
if (compare(element, target[mid]) < 0) {
max = mid;
} else {
@@ -212,18 +212,18 @@
///
/// Allows target to be the same list as [list], as long as it's not
/// overlapping the `start..end` range.
-void _mergeSort<T>(List<T> list, int compare(T a, T b), int start, int end,
+void _mergeSort<T>(List<T> list, int Function(T, T) compare, int start, int end,
List<T> target, int targetOffset) {
- int length = end - start;
+ var length = end - start;
if (length < _MERGE_SORT_LIMIT) {
_movingInsertionSort(list, compare, start, end, target, targetOffset);
return;
}
- int middle = start + (length >> 1);
- int firstLength = middle - start;
- int secondLength = end - middle;
+ var middle = start + (length >> 1);
+ var firstLength = middle - start;
+ var secondLength = end - middle;
// Here secondLength >= firstLength (differs by at most one).
- int targetMiddle = targetOffset + firstLength;
+ var targetMiddle = targetOffset + firstLength;
// Sort the second half into the end of the target area.
_mergeSort(list, compare, middle, end, target, targetMiddle);
// Sort the first half into the end of the source area.
@@ -242,7 +242,7 @@
/// This allows the merge to be stable if the first list contains elements
/// that started out earlier than the ones in [secondList]
void _merge<T>(
- int compare(T a, T b),
+ int Function(T, T) compare,
List<T> firstList,
int firstStart,
int firstEnd,
@@ -254,8 +254,8 @@
// No empty lists reaches here.
assert(firstStart < firstEnd);
assert(secondStart < secondEnd);
- int cursor1 = firstStart;
- int cursor2 = secondStart;
+ var cursor1 = firstStart;
+ var cursor2 = secondStart;
var firstElement = firstList[cursor1++];
var secondElement = secondList[cursor2++];
while (true) {
diff --git a/lib/src/canonicalized_map.dart b/lib/src/canonicalized_map.dart
index 80324b2..383c18f 100644
--- a/lib/src/canonicalized_map.dart
+++ b/lib/src/canonicalized_map.dart
@@ -24,7 +24,7 @@
final _IsValidKey _isValidKeyFn;
- final _base = Map<C, Pair<K, V>>();
+ final _base = <C, Pair<K, V>>{};
/// Creates an empty canonicalized map.
///
@@ -34,7 +34,8 @@
/// The [isValidKey] function is called before calling [canonicalize] for
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
- CanonicalizedMap(C canonicalize(K key), {bool isValidKey(Object key)})
+ CanonicalizedMap(C Function(K key) canonicalize,
+ {bool Function(Object key) isValidKey})
: _canonicalize = canonicalize,
_isValidKeyFn = isValidKey;
@@ -47,91 +48,113 @@
/// The [isValidKey] function is called before calling [canonicalize] for
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
- CanonicalizedMap.from(Map<K, V> other, C canonicalize(K key),
- {bool isValidKey(Object key)})
+ CanonicalizedMap.from(Map<K, V> other, C Function(K key) canonicalize,
+ {bool Function(Object key) isValidKey})
: _canonicalize = canonicalize,
_isValidKeyFn = isValidKey {
addAll(other);
}
+ @override
V operator [](Object key) {
if (!_isValidKey(key)) return null;
var pair = _base[_canonicalize(key as K)];
return pair == null ? null : pair.last;
}
+ @override
void operator []=(K key, V value) {
if (!_isValidKey(key)) return;
_base[_canonicalize(key)] = Pair(key, value);
}
+ @override
void addAll(Map<K, V> other) {
other.forEach((key, value) => this[key] = value);
}
+ @override
void addEntries(Iterable<MapEntry<K, V>> entries) => _base.addEntries(
entries.map((e) => MapEntry(_canonicalize(e.key), Pair(e.key, e.value))));
+ @override
Map<K2, V2> cast<K2, V2>() => _base.cast<K2, V2>();
+ @override
void clear() {
_base.clear();
}
+ @override
bool containsKey(Object key) {
if (!_isValidKey(key)) return false;
return _base.containsKey(_canonicalize(key as K));
}
+ @override
bool containsValue(Object value) =>
_base.values.any((pair) => pair.last == value);
+ @override
Iterable<MapEntry<K, V>> get entries =>
_base.entries.map((e) => MapEntry(e.value.first, e.value.last));
- void forEach(void f(K key, V value)) {
+ @override
+ void forEach(void Function(K, V) f) {
_base.forEach((key, pair) => f(pair.first, pair.last));
}
+ @override
bool get isEmpty => _base.isEmpty;
+ @override
bool get isNotEmpty => _base.isNotEmpty;
+ @override
Iterable<K> get keys => _base.values.map((pair) => pair.first);
+ @override
int get length => _base.length;
- Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> transform(K key, V value)) =>
+ @override
+ Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> Function(K, V) transform) =>
_base.map((_, pair) => transform(pair.first, pair.last));
- V putIfAbsent(K key, V ifAbsent()) {
+ @override
+ V putIfAbsent(K key, V Function() ifAbsent) {
return _base
.putIfAbsent(_canonicalize(key), () => Pair(key, ifAbsent()))
.last;
}
+ @override
V remove(Object key) {
if (!_isValidKey(key)) return null;
var pair = _base.remove(_canonicalize(key as K));
return pair == null ? null : pair.last;
}
- void removeWhere(bool test(K key, V value)) =>
+ @override
+ void removeWhere(bool Function(K key, V value) test) =>
_base.removeWhere((_, pair) => test(pair.first, pair.last));
@deprecated
Map<K2, V2> retype<K2, V2>() => cast<K2, V2>();
- V update(K key, V update(V value), {V ifAbsent()}) => _base
+ @override
+ V update(K key, V Function(V) update, {V Function() ifAbsent}) => _base
.update(_canonicalize(key), (pair) => Pair(key, update(pair.last)),
ifAbsent: ifAbsent == null ? null : () => Pair(key, ifAbsent()))
.last;
- void updateAll(V update(K key, V value)) => _base
+ @override
+ void updateAll(V Function(K key, V value) update) => _base
.updateAll((_, pair) => Pair(pair.first, update(pair.first, pair.last)));
+ @override
Iterable<V> get values => _base.values.map((pair) => pair.last);
+ @override
String toString() {
// Detect toString() cycles.
if (_isToStringVisiting(this)) {
@@ -142,7 +165,7 @@
try {
_toStringVisiting.add(this);
result.write('{');
- bool first = true;
+ var first = true;
forEach((k, v) {
if (!first) {
result.write(', ');
diff --git a/lib/src/combined_wrappers/combined_iterable.dart b/lib/src/combined_wrappers/combined_iterable.dart
index 3df5e82..ce19c20 100644
--- a/lib/src/combined_wrappers/combined_iterable.dart
+++ b/lib/src/combined_wrappers/combined_iterable.dart
@@ -18,16 +18,20 @@
/// Creates a combined view of [iterables].
const CombinedIterableView(this._iterables);
+ @override
Iterator<T> get iterator =>
_CombinedIterator<T>(_iterables.map((i) => i.iterator).iterator);
// Special cased contains/isEmpty/length since many iterables have an
// efficient implementation instead of running through the entire iterator.
+ @override
bool contains(Object element) => _iterables.any((i) => i.contains(element));
+ @override
bool get isEmpty => _iterables.every((i) => i.isEmpty);
+ @override
int get length => _iterables.fold(0, (length, i) => length + i.length);
}
@@ -43,8 +47,10 @@
_CombinedIterator(this._iterators);
+ @override
T get current => _iterators.current?.current;
+ @override
bool moveNext() {
var current = _iterators.current;
if (current != null && current.moveNext()) {
diff --git a/lib/src/combined_wrappers/combined_list.dart b/lib/src/combined_wrappers/combined_list.dart
index 593490e..961ea42 100644
--- a/lib/src/combined_wrappers/combined_list.dart
+++ b/lib/src/combined_wrappers/combined_list.dart
@@ -25,12 +25,15 @@
/// Creates a combined view of [lists].
CombinedListView(this._lists);
+ @override
set length(int length) {
_throw();
}
+ @override
int get length => _lists.fold(0, (length, list) => length + list.length);
+ @override
T operator [](int index) {
var initialIndex = index;
for (var i = 0; i < _lists.length; i++) {
@@ -43,24 +46,29 @@
throw RangeError.index(initialIndex, this, 'index', null, length);
}
+ @override
void operator []=(int index, T value) {
_throw();
}
+ @override
void clear() {
_throw();
}
+ @override
bool remove(Object element) {
_throw();
return null;
}
- void removeWhere(bool test(T element)) {
+ @override
+ void removeWhere(bool Function(T) test) {
_throw();
}
- void retainWhere(bool test(T element)) {
+ @override
+ void retainWhere(bool Function(T) test) {
_throw();
}
}
diff --git a/lib/src/combined_wrappers/combined_map.dart b/lib/src/combined_wrappers/combined_map.dart
index 386a6de..8e2f729 100644
--- a/lib/src/combined_wrappers/combined_map.dart
+++ b/lib/src/combined_wrappers/combined_map.dart
@@ -28,6 +28,7 @@
/// [List] or [Set] rather than a lazy iterable produced by `map()` et al.
CombinedMapView(this._maps);
+ @override
V operator [](Object key) {
for (var map in _maps) {
// Avoid two hash lookups on a positive hit.
@@ -53,6 +54,7 @@
/// Unlike most [Map] implementations, modifying an individual map while
/// iterating the keys will _sometimes_ throw. This behavior may change in
/// the future.
+ @override
Iterable<K> get keys => _DeduplicatingIterableView(
CombinedIterableView(_maps.map((m) => m.keys)));
}
@@ -63,6 +65,7 @@
const _DeduplicatingIterableView(this._iterable);
+ @override
Iterator<T> get iterator => _DeduplicatingIterator(_iterable.iterator);
// Special cased contains/isEmpty since many iterables have an efficient
@@ -71,8 +74,10 @@
// Note: We do not do this for `length` because we have to remove the
// duplicates.
+ @override
bool contains(Object element) => _iterable.contains(element);
+ @override
bool get isEmpty => _iterable.isEmpty;
}
@@ -84,8 +89,10 @@
_DeduplicatingIterator(this._iterator);
+ @override
T get current => _iterator.current;
+ @override
bool moveNext() {
while (_iterator.moveNext()) {
if (_emitted.add(current)) {
diff --git a/lib/src/comparators.dart b/lib/src/comparators.dart
index 5fc55b2..0d223c9 100644
--- a/lib/src/comparators.dart
+++ b/lib/src/comparators.dart
@@ -1,393 +1,393 @@
-// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-// Character constants.
-const int _zero = 0x30;
-const int _upperCaseA = 0x41;
-const int _upperCaseZ = 0x5a;
-const int _lowerCaseA = 0x61;
-const int _lowerCaseZ = 0x7a;
-const int _asciiCaseBit = 0x20;
-
-/// Checks if strings [a] and [b] differ only on the case of ASCII letters.
-///
-/// Strings are equal if they have the same length, and the characters at
-/// each index are the same, or they are ASCII letters where one is upper-case
-/// and the other is the lower-case version of the same letter.
-///
-/// The comparison does not ignore the case of non-ASCII letters, so
-/// an upper-case ae-ligature (Æ) is different from
-/// a lower case ae-ligature (æ).
-///
-/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
-/// for situations where the strings are known to be ASCII. Examples could
-/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
-/// strings with a known structure.
-bool equalsIgnoreAsciiCase(String a, String b) {
- if (a.length != b.length) return false;
- for (int i = 0; i < a.length; i++) {
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar == bChar) continue;
- // Quick-check for whether this may be different cases of the same letter.
- if (aChar ^ bChar != _asciiCaseBit) return false;
- // If it's possible, then check if either character is actually an ASCII
- // letter.
- int aCharLowerCase = aChar | _asciiCaseBit;
- if (_lowerCaseA <= aCharLowerCase && aCharLowerCase <= _lowerCaseZ) {
- continue;
- }
- return false;
- }
- return true;
-}
-
-/// Hash code for a string which is compatible with [equalsIgnoreAsciiCase].
-///
-/// The hash code is unaffected by changing the case of ASCII letters, but
-/// the case of non-ASCII letters do affect the result.
-int hashIgnoreAsciiCase(String string) {
- // Jenkins hash code ( http://en.wikipedia.org/wiki/Jenkins_hash_function).
- // adapted to smi values.
- // Same hash used by dart2js for strings, modified to ignore ASCII letter
- // case.
- int hash = 0;
- for (int i = 0; i < string.length; i++) {
- int char = string.codeUnitAt(i);
- // Convert lower-case ASCII letters to upper case.upper
- // This ensures that strings that differ only in case will have the
- // same hash code.
- if (_lowerCaseA <= char && char <= _lowerCaseZ) char -= _asciiCaseBit;
- hash = 0x1fffffff & (hash + char);
- hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
- hash >>= 6;
- }
- hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
- hash >>= 11;
- return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
-}
-
-/// Compares [a] and [b] lexically, converting ASCII letters to upper case.
-///
-/// Comparison treats all lower-case ASCII letters as upper-case letters,
-/// but does no case conversion for non-ASCII letters.
-///
-/// If two strings differ only on the case of ASCII letters, the one with the
-/// capital letter at the first difference will compare as less than the other
-/// string. This tie-breaking ensures that the comparison is a total ordering
-/// on strings and is compatible with equality.
-///
-/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
-/// for situations where the strings are known to be ASCII. Examples could
-/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
-/// strings with a known structure.
-int compareAsciiUpperCase(String a, String b) {
- int defaultResult = 0; // Returned if no difference found.
- for (int i = 0; i < a.length; i++) {
- if (i >= b.length) return 1;
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar == bChar) continue;
- // Upper-case if letters.
- int aUpperCase = aChar;
- int bUpperCase = bChar;
- if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) {
- aUpperCase -= _asciiCaseBit;
- }
- if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) {
- bUpperCase -= _asciiCaseBit;
- }
- if (aUpperCase != bUpperCase) return (aUpperCase - bUpperCase).sign;
- if (defaultResult == 0) defaultResult = (aChar - bChar);
- }
- if (b.length > a.length) return -1;
- return defaultResult.sign;
-}
-
-/// Compares [a] and [b] lexically, converting ASCII letters to lower case.
-///
-/// Comparison treats all upper-case ASCII letters as lower-case letters,
-/// but does no case conversion for non-ASCII letters.
-///
-/// If two strings differ only on the case of ASCII letters, the one with the
-/// capital letter at the first difference will compare as less than the other
-/// string. This tie-breaking ensures that the comparison is a total ordering
-/// on strings.
-///
-/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
-/// for situations where the strings are known to be ASCII. Examples could
-/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
-/// strings with a known structure.
-int compareAsciiLowerCase(String a, String b) {
- int defaultResult = 0;
- for (int i = 0; i < a.length; i++) {
- if (i >= b.length) return 1;
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar == bChar) continue;
- int aLowerCase = aChar;
- int bLowerCase = bChar;
- // Upper case if ASCII letters.
- if (_upperCaseA <= bChar && bChar <= _upperCaseZ) {
- bLowerCase += _asciiCaseBit;
- }
- if (_upperCaseA <= aChar && aChar <= _upperCaseZ) {
- aLowerCase += _asciiCaseBit;
- }
- if (aLowerCase != bLowerCase) return (aLowerCase - bLowerCase).sign;
- if (defaultResult == 0) defaultResult = aChar - bChar;
- }
- if (b.length > a.length) return -1;
- return defaultResult.sign;
-}
-
-/// Compares strings [a] and [b] according to [natural sort ordering][].
-///
-/// A natural sort ordering is a lexical ordering where embedded
-/// numerals (digit sequences) are treated as a single unit and ordered by
-/// numerical value.
-/// This means that `"a10b"` will be ordered after `"a7b"` in natural
-/// ordering, where lexical ordering would put the `1` before the `7`, ignoring
-/// that the `1` is part of a larger number.
-///
-/// Example:
-/// The following strings are in the order they would be sorted by using this
-/// comparison function:
-///
-/// "a", "a0", "a0b", "a1", "a01", "a9", "a10", "a100", "a100b", "aa"
-///
-/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
-int compareNatural(String a, String b) {
- for (int i = 0; i < a.length; i++) {
- if (i >= b.length) return 1;
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar != bChar) {
- return _compareNaturally(a, b, i, aChar, bChar);
- }
- }
- if (b.length > a.length) return -1;
- return 0;
-}
-
-/// Compares strings [a] and [b] according to lower-case
-/// [natural sort ordering][].
-///
-/// ASCII letters are converted to lower case before being compared, like
-/// for [compareAsciiLowerCase], then the result is compared like for
-/// [compareNatural].
-///
-/// If two strings differ only on the case of ASCII letters, the one with the
-/// capital letter at the first difference will compare as less than the other
-/// string. This tie-breaking ensures that the comparison is a total ordering
-/// on strings.
-///
-/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
-int compareAsciiLowerCaseNatural(String a, String b) {
- int defaultResult = 0; // Returned if no difference found.
- for (int i = 0; i < a.length; i++) {
- if (i >= b.length) return 1;
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar == bChar) continue;
- int aLowerCase = aChar;
- int bLowerCase = bChar;
- if (_upperCaseA <= aChar && aChar <= _upperCaseZ) {
- aLowerCase += _asciiCaseBit;
- }
- if (_upperCaseA <= bChar && bChar <= _upperCaseZ) {
- bLowerCase += _asciiCaseBit;
- }
- if (aLowerCase != bLowerCase) {
- return _compareNaturally(a, b, i, aLowerCase, bLowerCase);
- }
- if (defaultResult == 0) defaultResult = aChar - bChar;
- }
- if (b.length > a.length) return -1;
- return defaultResult.sign;
-}
-
-/// Compares strings [a] and [b] according to upper-case
-/// [natural sort ordering][].
-///
-/// ASCII letters are converted to upper case before being compared, like
-/// for [compareAsciiUpperCase], then the result is compared like for
-/// [compareNatural].
-///
-/// If two strings differ only on the case of ASCII letters, the one with the
-/// capital letter at the first difference will compare as less than the other
-/// string. This tie-breaking ensures that the comparison is a total ordering
-/// on strings
-///
-/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
-int compareAsciiUpperCaseNatural(String a, String b) {
- int defaultResult = 0;
- for (int i = 0; i < a.length; i++) {
- if (i >= b.length) return 1;
- var aChar = a.codeUnitAt(i);
- var bChar = b.codeUnitAt(i);
- if (aChar == bChar) continue;
- int aUpperCase = aChar;
- int bUpperCase = bChar;
- if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) {
- aUpperCase -= _asciiCaseBit;
- }
- if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) {
- bUpperCase -= _asciiCaseBit;
- }
- if (aUpperCase != bUpperCase) {
- return _compareNaturally(a, b, i, aUpperCase, bUpperCase);
- }
- if (defaultResult == 0) defaultResult = aChar - bChar;
- }
- if (b.length > a.length) return -1;
- return defaultResult.sign;
-}
-
-/// Check for numbers overlapping the current mismatched characters.
-///
-/// If both [aChar] and [bChar] are digits, use numerical comparison.
-/// Check if the previous characters is a non-zero number, and if not,
-/// skip - but count - leading zeros before comparing numbers.
-///
-/// If one is a digit and the other isn't, check if the previous character
-/// is a digit, and if so, the the one with the digit is the greater number.
-///
-/// Otherwise just returns the difference between [aChar] and [bChar].
-int _compareNaturally(String a, String b, int index, int aChar, int bChar) {
- assert(aChar != bChar);
- var aIsDigit = _isDigit(aChar);
- var bIsDigit = _isDigit(bChar);
- if (aIsDigit) {
- if (bIsDigit) {
- return _compareNumerically(a, b, aChar, bChar, index);
- } else if (index > 0 && _isDigit(a.codeUnitAt(index - 1))) {
- // aChar is the continuation of a longer number.
- return 1;
- }
- } else if (bIsDigit && index > 0 && _isDigit(b.codeUnitAt(index - 1))) {
- // bChar is the continuation of a longer number.
- return -1;
- }
- // Characters are both non-digits, or not continuation of earlier number.
- return (aChar - bChar).sign;
-}
-
-/// Compare numbers overlapping [aChar] and [bChar] numerically.
-///
-/// If the numbers have the same numerical value, but one has more leading
-/// zeros, the longer number is considered greater than the shorter one.
-///
-/// This ensures a total ordering on strings compatible with equality.
-int _compareNumerically(String a, String b, int aChar, int bChar, int index) {
- // Both are digits. Find the first significant different digit, then find
- // the length of the numbers.
- if (_isNonZeroNumberSuffix(a, index)) {
- // Part of a longer number, differs at this index, just count the length.
- int result = _compareDigitCount(a, b, index, index);
- if (result != 0) return result;
- // If same length, the current character is the most significant differing
- // digit.
- return (aChar - bChar).sign;
- }
- // Not part of larger (non-zero) number, so skip leading zeros before
- // comparing numbers.
- int aIndex = index;
- int bIndex = index;
- if (aChar == _zero) {
- do {
- aIndex++;
- if (aIndex == a.length) return -1; // number in a is zero, b is not.
- aChar = a.codeUnitAt(aIndex);
- } while (aChar == _zero);
- if (!_isDigit(aChar)) return -1;
- } else if (bChar == _zero) {
- do {
- bIndex++;
- if (bIndex == b.length) return 1; // number in b is zero, a is not.
- bChar = b.codeUnitAt(bIndex);
- } while (bChar == _zero);
- if (!_isDigit(bChar)) return 1;
- }
- if (aChar != bChar) {
- int result = _compareDigitCount(a, b, aIndex, bIndex);
- if (result != 0) return result;
- return (aChar - bChar).sign;
- }
- // Same leading digit, one had more leading zeros.
- // Compare digits until reaching a difference.
- while (true) {
- var aIsDigit = false;
- var bIsDigit = false;
- aChar = 0;
- bChar = 0;
- if (++aIndex < a.length) {
- aChar = a.codeUnitAt(aIndex);
- aIsDigit = _isDigit(aChar);
- }
- if (++bIndex < b.length) {
- bChar = b.codeUnitAt(bIndex);
- bIsDigit = _isDigit(bChar);
- }
- if (aIsDigit) {
- if (bIsDigit) {
- if (aChar == bChar) continue;
- // First different digit found.
- break;
- }
- // bChar is non-digit, so a has longer number.
- return 1;
- } else if (bIsDigit) {
- return -1; // b has longer number.
- } else {
- // Neither is digit, so numbers had same numerical value.
- // Fall back on number of leading zeros
- // (reflected by difference in indices).
- return (aIndex - bIndex).sign;
- }
- }
- // At first differing digits.
- int result = _compareDigitCount(a, b, aIndex, bIndex);
- if (result != 0) return result;
- return (aChar - bChar).sign;
-}
-
-/// Checks which of [a] and [b] has the longest sequence of digits.
-///
-/// Starts counting from `i + 1` and `j + 1` (assumes that `a[i]` and `b[j]` are
-/// both already known to be digits).
-int _compareDigitCount(String a, String b, int i, int j) {
- while (++i < a.length) {
- bool aIsDigit = _isDigit(a.codeUnitAt(i));
- if (++j == b.length) return aIsDigit ? 1 : 0;
- bool bIsDigit = _isDigit(b.codeUnitAt(j));
- if (aIsDigit) {
- if (bIsDigit) continue;
- return 1;
- } else if (bIsDigit) {
- return -1;
- } else {
- return 0;
- }
- }
- if (++j < b.length && _isDigit(b.codeUnitAt(j))) {
- return -1;
- }
- return 0;
-}
-
-bool _isDigit(int charCode) => (charCode ^ _zero) <= 9;
-
-/// Check if the digit at [index] is continuing a non-zero number.
-///
-/// If there is no non-zero digits before, then leading zeros at [index]
-/// are also ignored when comparing numerically. If there is a non-zero digit
-/// before, then zeros at [index] are significant.
-bool _isNonZeroNumberSuffix(String string, int index) {
- while (--index >= 0) {
- int char = string.codeUnitAt(index);
- if (char != _zero) return _isDigit(char);
- }
- return false;
-}
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Character constants.
+const int _zero = 0x30;
+const int _upperCaseA = 0x41;
+const int _upperCaseZ = 0x5a;
+const int _lowerCaseA = 0x61;
+const int _lowerCaseZ = 0x7a;
+const int _asciiCaseBit = 0x20;
+
+/// Checks if strings [a] and [b] differ only on the case of ASCII letters.
+///
+/// Strings are equal if they have the same length, and the characters at
+/// each index are the same, or they are ASCII letters where one is upper-case
+/// and the other is the lower-case version of the same letter.
+///
+/// The comparison does not ignore the case of non-ASCII letters, so
+/// an upper-case ae-ligature (Æ) is different from
+/// a lower case ae-ligature (æ).
+///
+/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
+/// for situations where the strings are known to be ASCII. Examples could
+/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
+/// strings with a known structure.
+bool equalsIgnoreAsciiCase(String a, String b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++) {
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar == bChar) continue;
+ // Quick-check for whether this may be different cases of the same letter.
+ if (aChar ^ bChar != _asciiCaseBit) return false;
+ // If it's possible, then check if either character is actually an ASCII
+ // letter.
+ var aCharLowerCase = aChar | _asciiCaseBit;
+ if (_lowerCaseA <= aCharLowerCase && aCharLowerCase <= _lowerCaseZ) {
+ continue;
+ }
+ return false;
+ }
+ return true;
+}
+
+/// Hash code for a string which is compatible with [equalsIgnoreAsciiCase].
+///
+/// The hash code is unaffected by changing the case of ASCII letters, but
+/// the case of non-ASCII letters do affect the result.
+int hashIgnoreAsciiCase(String string) {
+ // Jenkins hash code ( http://en.wikipedia.org/wiki/Jenkins_hash_function).
+ // adapted to smi values.
+ // Same hash used by dart2js for strings, modified to ignore ASCII letter
+ // case.
+ var hash = 0;
+ for (var i = 0; i < string.length; i++) {
+ var char = string.codeUnitAt(i);
+ // Convert lower-case ASCII letters to upper case.upper
+ // This ensures that strings that differ only in case will have the
+ // same hash code.
+ if (_lowerCaseA <= char && char <= _lowerCaseZ) char -= _asciiCaseBit;
+ hash = 0x1fffffff & (hash + char);
+ hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
+ hash >>= 6;
+ }
+ hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
+ hash >>= 11;
+ return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
+}
+
+/// Compares [a] and [b] lexically, converting ASCII letters to upper case.
+///
+/// Comparison treats all lower-case ASCII letters as upper-case letters,
+/// but does no case conversion for non-ASCII letters.
+///
+/// If two strings differ only on the case of ASCII letters, the one with the
+/// capital letter at the first difference will compare as less than the other
+/// string. This tie-breaking ensures that the comparison is a total ordering
+/// on strings and is compatible with equality.
+///
+/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
+/// for situations where the strings are known to be ASCII. Examples could
+/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
+/// strings with a known structure.
+int compareAsciiUpperCase(String a, String b) {
+ var defaultResult = 0; // Returned if no difference found.
+ for (var i = 0; i < a.length; i++) {
+ if (i >= b.length) return 1;
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar == bChar) continue;
+ // Upper-case if letters.
+ var aUpperCase = aChar;
+ var bUpperCase = bChar;
+ if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) {
+ aUpperCase -= _asciiCaseBit;
+ }
+ if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) {
+ bUpperCase -= _asciiCaseBit;
+ }
+ if (aUpperCase != bUpperCase) return (aUpperCase - bUpperCase).sign;
+ if (defaultResult == 0) defaultResult = (aChar - bChar);
+ }
+ if (b.length > a.length) return -1;
+ return defaultResult.sign;
+}
+
+/// Compares [a] and [b] lexically, converting ASCII letters to lower case.
+///
+/// Comparison treats all upper-case ASCII letters as lower-case letters,
+/// but does no case conversion for non-ASCII letters.
+///
+/// If two strings differ only on the case of ASCII letters, the one with the
+/// capital letter at the first difference will compare as less than the other
+/// string. This tie-breaking ensures that the comparison is a total ordering
+/// on strings.
+///
+/// Ignoring non-ASCII letters is not generally a good idea, but it makes sense
+/// for situations where the strings are known to be ASCII. Examples could
+/// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar
+/// strings with a known structure.
+int compareAsciiLowerCase(String a, String b) {
+ var defaultResult = 0;
+ for (var i = 0; i < a.length; i++) {
+ if (i >= b.length) return 1;
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar == bChar) continue;
+ var aLowerCase = aChar;
+ var bLowerCase = bChar;
+ // Upper case if ASCII letters.
+ if (_upperCaseA <= bChar && bChar <= _upperCaseZ) {
+ bLowerCase += _asciiCaseBit;
+ }
+ if (_upperCaseA <= aChar && aChar <= _upperCaseZ) {
+ aLowerCase += _asciiCaseBit;
+ }
+ if (aLowerCase != bLowerCase) return (aLowerCase - bLowerCase).sign;
+ if (defaultResult == 0) defaultResult = aChar - bChar;
+ }
+ if (b.length > a.length) return -1;
+ return defaultResult.sign;
+}
+
+/// Compares strings [a] and [b] according to [natural sort ordering][].
+///
+/// A natural sort ordering is a lexical ordering where embedded
+/// numerals (digit sequences) are treated as a single unit and ordered by
+/// numerical value.
+/// This means that `"a10b"` will be ordered after `"a7b"` in natural
+/// ordering, where lexical ordering would put the `1` before the `7`, ignoring
+/// that the `1` is part of a larger number.
+///
+/// Example:
+/// The following strings are in the order they would be sorted by using this
+/// comparison function:
+///
+/// "a", "a0", "a0b", "a1", "a01", "a9", "a10", "a100", "a100b", "aa"
+///
+/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
+int compareNatural(String a, String b) {
+ for (var i = 0; i < a.length; i++) {
+ if (i >= b.length) return 1;
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar != bChar) {
+ return _compareNaturally(a, b, i, aChar, bChar);
+ }
+ }
+ if (b.length > a.length) return -1;
+ return 0;
+}
+
+/// Compares strings [a] and [b] according to lower-case
+/// [natural sort ordering][].
+///
+/// ASCII letters are converted to lower case before being compared, like
+/// for [compareAsciiLowerCase], then the result is compared like for
+/// [compareNatural].
+///
+/// If two strings differ only on the case of ASCII letters, the one with the
+/// capital letter at the first difference will compare as less than the other
+/// string. This tie-breaking ensures that the comparison is a total ordering
+/// on strings.
+///
+/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
+int compareAsciiLowerCaseNatural(String a, String b) {
+ var defaultResult = 0; // Returned if no difference found.
+ for (var i = 0; i < a.length; i++) {
+ if (i >= b.length) return 1;
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar == bChar) continue;
+ var aLowerCase = aChar;
+ var bLowerCase = bChar;
+ if (_upperCaseA <= aChar && aChar <= _upperCaseZ) {
+ aLowerCase += _asciiCaseBit;
+ }
+ if (_upperCaseA <= bChar && bChar <= _upperCaseZ) {
+ bLowerCase += _asciiCaseBit;
+ }
+ if (aLowerCase != bLowerCase) {
+ return _compareNaturally(a, b, i, aLowerCase, bLowerCase);
+ }
+ if (defaultResult == 0) defaultResult = aChar - bChar;
+ }
+ if (b.length > a.length) return -1;
+ return defaultResult.sign;
+}
+
+/// Compares strings [a] and [b] according to upper-case
+/// [natural sort ordering][].
+///
+/// ASCII letters are converted to upper case before being compared, like
+/// for [compareAsciiUpperCase], then the result is compared like for
+/// [compareNatural].
+///
+/// If two strings differ only on the case of ASCII letters, the one with the
+/// capital letter at the first difference will compare as less than the other
+/// string. This tie-breaking ensures that the comparison is a total ordering
+/// on strings
+///
+/// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order
+int compareAsciiUpperCaseNatural(String a, String b) {
+ var defaultResult = 0;
+ for (var i = 0; i < a.length; i++) {
+ if (i >= b.length) return 1;
+ var aChar = a.codeUnitAt(i);
+ var bChar = b.codeUnitAt(i);
+ if (aChar == bChar) continue;
+ var aUpperCase = aChar;
+ var bUpperCase = bChar;
+ if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) {
+ aUpperCase -= _asciiCaseBit;
+ }
+ if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) {
+ bUpperCase -= _asciiCaseBit;
+ }
+ if (aUpperCase != bUpperCase) {
+ return _compareNaturally(a, b, i, aUpperCase, bUpperCase);
+ }
+ if (defaultResult == 0) defaultResult = aChar - bChar;
+ }
+ if (b.length > a.length) return -1;
+ return defaultResult.sign;
+}
+
+/// Check for numbers overlapping the current mismatched characters.
+///
+/// If both [aChar] and [bChar] are digits, use numerical comparison.
+/// Check if the previous characters is a non-zero number, and if not,
+/// skip - but count - leading zeros before comparing numbers.
+///
+/// If one is a digit and the other isn't, check if the previous character
+/// is a digit, and if so, the the one with the digit is the greater number.
+///
+/// Otherwise just returns the difference between [aChar] and [bChar].
+int _compareNaturally(String a, String b, int index, int aChar, int bChar) {
+ assert(aChar != bChar);
+ var aIsDigit = _isDigit(aChar);
+ var bIsDigit = _isDigit(bChar);
+ if (aIsDigit) {
+ if (bIsDigit) {
+ return _compareNumerically(a, b, aChar, bChar, index);
+ } else if (index > 0 && _isDigit(a.codeUnitAt(index - 1))) {
+ // aChar is the continuation of a longer number.
+ return 1;
+ }
+ } else if (bIsDigit && index > 0 && _isDigit(b.codeUnitAt(index - 1))) {
+ // bChar is the continuation of a longer number.
+ return -1;
+ }
+ // Characters are both non-digits, or not continuation of earlier number.
+ return (aChar - bChar).sign;
+}
+
+/// Compare numbers overlapping [aChar] and [bChar] numerically.
+///
+/// If the numbers have the same numerical value, but one has more leading
+/// zeros, the longer number is considered greater than the shorter one.
+///
+/// This ensures a total ordering on strings compatible with equality.
+int _compareNumerically(String a, String b, int aChar, int bChar, int index) {
+ // Both are digits. Find the first significant different digit, then find
+ // the length of the numbers.
+ if (_isNonZeroNumberSuffix(a, index)) {
+ // Part of a longer number, differs at this index, just count the length.
+ var result = _compareDigitCount(a, b, index, index);
+ if (result != 0) return result;
+ // If same length, the current character is the most significant differing
+ // digit.
+ return (aChar - bChar).sign;
+ }
+ // Not part of larger (non-zero) number, so skip leading zeros before
+ // comparing numbers.
+ var aIndex = index;
+ var bIndex = index;
+ if (aChar == _zero) {
+ do {
+ aIndex++;
+ if (aIndex == a.length) return -1; // number in a is zero, b is not.
+ aChar = a.codeUnitAt(aIndex);
+ } while (aChar == _zero);
+ if (!_isDigit(aChar)) return -1;
+ } else if (bChar == _zero) {
+ do {
+ bIndex++;
+ if (bIndex == b.length) return 1; // number in b is zero, a is not.
+ bChar = b.codeUnitAt(bIndex);
+ } while (bChar == _zero);
+ if (!_isDigit(bChar)) return 1;
+ }
+ if (aChar != bChar) {
+ var result = _compareDigitCount(a, b, aIndex, bIndex);
+ if (result != 0) return result;
+ return (aChar - bChar).sign;
+ }
+ // Same leading digit, one had more leading zeros.
+ // Compare digits until reaching a difference.
+ while (true) {
+ var aIsDigit = false;
+ var bIsDigit = false;
+ aChar = 0;
+ bChar = 0;
+ if (++aIndex < a.length) {
+ aChar = a.codeUnitAt(aIndex);
+ aIsDigit = _isDigit(aChar);
+ }
+ if (++bIndex < b.length) {
+ bChar = b.codeUnitAt(bIndex);
+ bIsDigit = _isDigit(bChar);
+ }
+ if (aIsDigit) {
+ if (bIsDigit) {
+ if (aChar == bChar) continue;
+ // First different digit found.
+ break;
+ }
+ // bChar is non-digit, so a has longer number.
+ return 1;
+ } else if (bIsDigit) {
+ return -1; // b has longer number.
+ } else {
+ // Neither is digit, so numbers had same numerical value.
+ // Fall back on number of leading zeros
+ // (reflected by difference in indices).
+ return (aIndex - bIndex).sign;
+ }
+ }
+ // At first differing digits.
+ var result = _compareDigitCount(a, b, aIndex, bIndex);
+ if (result != 0) return result;
+ return (aChar - bChar).sign;
+}
+
+/// Checks which of [a] and [b] has the longest sequence of digits.
+///
+/// Starts counting from `i + 1` and `j + 1` (assumes that `a[i]` and `b[j]` are
+/// both already known to be digits).
+int _compareDigitCount(String a, String b, int i, int j) {
+ while (++i < a.length) {
+ var aIsDigit = _isDigit(a.codeUnitAt(i));
+ if (++j == b.length) return aIsDigit ? 1 : 0;
+ var bIsDigit = _isDigit(b.codeUnitAt(j));
+ if (aIsDigit) {
+ if (bIsDigit) continue;
+ return 1;
+ } else if (bIsDigit) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ if (++j < b.length && _isDigit(b.codeUnitAt(j))) {
+ return -1;
+ }
+ return 0;
+}
+
+bool _isDigit(int charCode) => (charCode ^ _zero) <= 9;
+
+/// Check if the digit at [index] is continuing a non-zero number.
+///
+/// If there is no non-zero digits before, then leading zeros at [index]
+/// are also ignored when comparing numerically. If there is a non-zero digit
+/// before, then zeros at [index] are significant.
+bool _isNonZeroNumberSuffix(String string, int index) {
+ while (--index >= 0) {
+ var char = string.codeUnitAt(index);
+ if (char != _zero) return _isDigit(char);
+ }
+ return false;
+}
diff --git a/lib/src/empty_unmodifiable_set.dart b/lib/src/empty_unmodifiable_set.dart
index 2c9ed30..86cbbb4 100644
--- a/lib/src/empty_unmodifiable_set.dart
+++ b/lib/src/empty_unmodifiable_set.dart
@@ -12,34 +12,57 @@
class EmptyUnmodifiableSet<E> extends IterableBase<E>
implements UnmodifiableSetView<E> {
static T _throw<T>() {
- throw UnsupportedError("Cannot modify an unmodifiable Set");
+ throw UnsupportedError('Cannot modify an unmodifiable Set');
}
+ @override
Iterator<E> get iterator => Iterable<E>.empty().iterator;
+ @override
int get length => 0;
const EmptyUnmodifiableSet();
+ @override
EmptyUnmodifiableSet<T> cast<T>() => EmptyUnmodifiableSet<T>();
+ @override
bool contains(Object element) => false;
+ @override
bool containsAll(Iterable<Object> other) => other.isEmpty;
+ @override
Iterable<E> followedBy(Iterable<E> other) => Set.from(other);
+ @override
E lookup(Object element) => null;
@deprecated
+ @override
EmptyUnmodifiableSet<T> retype<T>() => EmptyUnmodifiableSet<T>();
- E singleWhere(bool test(E element), {E orElse()}) => super.singleWhere(test);
+ @override
+ E singleWhere(bool Function(E) test, {E Function() orElse}) =>
+ super.singleWhere(test);
+ @override
Iterable<T> whereType<T>() => EmptyUnmodifiableSet<T>();
- Set<E> toSet() => Set();
+ @override
+ Set<E> toSet() => {};
+ @override
Set<E> union(Set<E> other) => Set.from(other);
- Set<E> intersection(Set<Object> other) => Set();
- Set<E> difference(Set<Object> other) => Set();
+ @override
+ Set<E> intersection(Set<Object> other) => {};
+ @override
+ Set<E> difference(Set<Object> other) => {};
+ @override
bool add(E value) => _throw();
+ @override
void addAll(Iterable<E> elements) => _throw();
+ @override
void clear() => _throw();
+ @override
bool remove(Object element) => _throw();
+ @override
void removeAll(Iterable<Object> elements) => _throw();
- void removeWhere(bool test(E element)) => _throw();
- void retainWhere(bool test(E element)) => _throw();
+ @override
+ void removeWhere(bool Function(E) test) => _throw();
+ @override
+ void retainWhere(bool Function(E) test) => _throw();
+ @override
void retainAll(Iterable<Object> elements) => _throw();
}
diff --git a/lib/src/equality.dart b/lib/src/equality.dart
index 5f4038a..439d526 100644
--- a/lib/src/equality.dart
+++ b/lib/src/equality.dart
@@ -2,9 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:collection";
+import 'dart:collection';
-import "comparators.dart";
+import 'comparators.dart';
const int _HASH_MASK = 0x7fffffff;
@@ -55,14 +55,18 @@
// Determines equality between two values of F.
final Equality<F> _inner;
- EqualityBy(F getKey(E object), [Equality<F> inner = const DefaultEquality()])
+ EqualityBy(F Function(E) getKey,
+ [Equality<F> inner = const DefaultEquality()])
: _getKey = getKey,
_inner = inner;
+ @override
bool equals(E e1, E e2) => _inner.equals(_getKey(e1), _getKey(e2));
+ @override
int hash(E e) => _inner.hash(_getKey(e));
+ @override
bool isValidKey(Object o) {
if (o is E) {
final value = _getKey(o);
@@ -82,16 +86,22 @@
/// compile-time constant, while still allowing the class to be used at runtime.
class DefaultEquality<E> implements Equality<E> {
const DefaultEquality();
+ @override
bool equals(Object e1, Object e2) => e1 == e2;
+ @override
int hash(Object e) => e.hashCode;
+ @override
bool isValidKey(Object o) => true;
}
/// Equality of objects that compares only the identity of the objects.
class IdentityEquality<E> implements Equality<E> {
const IdentityEquality();
+ @override
bool equals(E e1, E e2) => identical(e1, e2);
+ @override
int hash(E e) => identityHashCode(e);
+ @override
bool isValidKey(Object o) => true;
}
@@ -108,25 +118,27 @@
[Equality<E> elementEquality = const DefaultEquality()])
: _elementEquality = elementEquality;
+ @override
bool equals(Iterable<E> elements1, Iterable<E> elements2) {
if (identical(elements1, elements2)) return true;
if (elements1 == null || elements2 == null) return false;
var it1 = elements1.iterator;
var it2 = elements2.iterator;
while (true) {
- bool hasNext = it1.moveNext();
+ var hasNext = it1.moveNext();
if (hasNext != it2.moveNext()) return false;
if (!hasNext) return true;
if (!_elementEquality.equals(it1.current, it2.current)) return false;
}
}
+ @override
int hash(Iterable<E> elements) {
if (elements == null) return null.hashCode;
// Jenkins's one-at-a-time hash function.
- int hash = 0;
- for (E element in elements) {
- int c = _elementEquality.hash(element);
+ var hash = 0;
+ for (var element in elements) {
+ var c = _elementEquality.hash(element);
hash = (hash + c) & _HASH_MASK;
hash = (hash + (hash << 10)) & _HASH_MASK;
hash ^= (hash >> 6);
@@ -137,6 +149,7 @@
return hash;
}
+ @override
bool isValidKey(Object o) => o is Iterable<E>;
}
@@ -156,25 +169,27 @@
const ListEquality([Equality<E> elementEquality = const DefaultEquality()])
: _elementEquality = elementEquality;
+ @override
bool equals(List<E> list1, List<E> list2) {
if (identical(list1, list2)) return true;
if (list1 == null || list2 == null) return false;
- int length = list1.length;
+ var length = list1.length;
if (length != list2.length) return false;
- for (int i = 0; i < length; i++) {
+ for (var i = 0; i < length; i++) {
if (!_elementEquality.equals(list1[i], list2[i])) return false;
}
return true;
}
+ @override
int hash(List<E> list) {
if (list == null) return null.hashCode;
// Jenkins's one-at-a-time hash function.
// This code is almost identical to the one in IterableEquality, except
// that it uses indexing instead of iterating to get the elements.
- int hash = 0;
- for (int i = 0; i < list.length; i++) {
- int c = _elementEquality.hash(list[i]);
+ var hash = 0;
+ for (var i = 0; i < list.length; i++) {
+ var c = _elementEquality.hash(list[i]);
hash = (hash + c) & _HASH_MASK;
hash = (hash + (hash << 10)) & _HASH_MASK;
hash ^= (hash >> 6);
@@ -185,6 +200,7 @@
return hash;
}
+ @override
bool isValidKey(Object o) => o is List<E>;
}
@@ -194,22 +210,22 @@
const _UnorderedEquality(this._elementEquality);
+ @override
bool equals(T elements1, T elements2) {
if (identical(elements1, elements2)) return true;
if (elements1 == null || elements2 == null) return false;
- HashMap<E, int> counts = HashMap(
+ var counts = HashMap(
equals: _elementEquality.equals,
hashCode: _elementEquality.hash,
isValidKey: _elementEquality.isValidKey);
- int length = 0;
+ var length = 0;
for (var e in elements1) {
- int count = counts[e];
- if (count == null) count = 0;
+ var count = counts[e] ?? 0;
counts[e] = count + 1;
length++;
}
for (var e in elements2) {
- int count = counts[e];
+ var count = counts[e];
if (count == null || count == 0) return false;
counts[e] = count - 1;
length--;
@@ -217,11 +233,12 @@
return length == 0;
}
+ @override
int hash(T elements) {
if (elements == null) return null.hashCode;
- int hash = 0;
+ var hash = 0;
for (E element in elements) {
- int c = _elementEquality.hash(element);
+ var c = _elementEquality.hash(element);
hash = (hash + c) & _HASH_MASK;
}
hash = (hash + (hash << 3)) & _HASH_MASK;
@@ -241,6 +258,7 @@
[Equality<E> elementEquality = const DefaultEquality()])
: super(elementEquality);
+ @override
bool isValidKey(Object o) => o is Iterable<E>;
}
@@ -260,6 +278,7 @@
const SetEquality([Equality<E> elementEquality = const DefaultEquality()])
: super(elementEquality);
+ @override
bool isValidKey(Object o) => o is Set<E>;
}
@@ -273,11 +292,13 @@
final value;
_MapEntry(this.equality, this.key, this.value);
+ @override
int get hashCode =>
(3 * equality._keyEquality.hash(key) +
7 * equality._valueEquality.hash(value)) &
_HASH_MASK;
+ @override
bool operator ==(Object other) =>
other is _MapEntry &&
equality._keyEquality.equals(key, other.key) &&
@@ -301,33 +322,34 @@
: _keyEquality = keys,
_valueEquality = values;
+ @override
bool equals(Map<K, V> map1, Map<K, V> map2) {
if (identical(map1, map2)) return true;
if (map1 == null || map2 == null) return false;
- int length = map1.length;
+ var length = map1.length;
if (length != map2.length) return false;
Map<_MapEntry, int> equalElementCounts = HashMap();
- for (K key in map1.keys) {
- _MapEntry entry = _MapEntry(this, key, map1[key]);
- int count = equalElementCounts[entry];
- if (count == null) count = 0;
+ for (var key in map1.keys) {
+ var entry = _MapEntry(this, key, map1[key]);
+ var count = equalElementCounts[entry] ?? 0;
equalElementCounts[entry] = count + 1;
}
- for (K key in map2.keys) {
- _MapEntry entry = _MapEntry(this, key, map2[key]);
- int count = equalElementCounts[entry];
+ for (var key in map2.keys) {
+ var entry = _MapEntry(this, key, map2[key]);
+ var count = equalElementCounts[entry];
if (count == null || count == 0) return false;
equalElementCounts[entry] = count - 1;
}
return true;
}
+ @override
int hash(Map<K, V> map) {
if (map == null) return null.hashCode;
- int hash = 0;
- for (K key in map.keys) {
- int keyHash = _keyEquality.hash(key);
- int valueHash = _valueEquality.hash(map[key]);
+ var hash = 0;
+ for (var key in map.keys) {
+ var keyHash = _keyEquality.hash(key);
+ var valueHash = _valueEquality.hash(map[key]);
hash = (hash + 3 * keyHash + 7 * valueHash) & _HASH_MASK;
}
hash = (hash + (hash << 3)) & _HASH_MASK;
@@ -336,6 +358,7 @@
return hash;
}
+ @override
bool isValidKey(Object o) => o is Map<K, V>;
}
@@ -359,22 +382,25 @@
const MultiEquality(Iterable<Equality<E>> equalities)
: _equalities = equalities;
+ @override
bool equals(E e1, E e2) {
- for (Equality<E> eq in _equalities) {
+ for (var eq in _equalities) {
if (eq.isValidKey(e1)) return eq.isValidKey(e2) && eq.equals(e1, e2);
}
return false;
}
+ @override
int hash(E e) {
- for (Equality<E> eq in _equalities) {
+ for (var eq in _equalities) {
if (eq.isValidKey(e)) return eq.hash(e);
}
return 0;
}
+ @override
bool isValidKey(Object o) {
- for (Equality<E> eq in _equalities) {
+ for (var eq in _equalities) {
if (eq.isValidKey(o)) return true;
}
return false;
@@ -411,6 +437,7 @@
: _base = base,
_unordered = true;
+ @override
bool equals(e1, e2) {
if (e1 is Set) {
return e2 is Set && SetEquality(this).equals(e1, e2);
@@ -432,6 +459,7 @@
return _base.equals(e1, e2);
}
+ @override
int hash(Object o) {
if (o is Set) return SetEquality(this).hash(o);
if (o is Map) return MapEquality(keys: this, values: this).hash(o);
@@ -444,6 +472,7 @@
return _base.hash(o);
}
+ @override
bool isValidKey(Object o) => o is Iterable || o is Map || _base.isValidKey(o);
}
@@ -453,10 +482,13 @@
class CaseInsensitiveEquality implements Equality<String> {
const CaseInsensitiveEquality();
+ @override
bool equals(String string1, String string2) =>
equalsIgnoreAsciiCase(string1, string2);
+ @override
int hash(String string) => hashIgnoreAsciiCase(string);
+ @override
bool isValidKey(Object object) => object is String;
}
diff --git a/lib/src/functions.dart b/lib/src/functions.dart
index 83e0493..d200a0b 100644
--- a/lib/src/functions.dart
+++ b/lib/src/functions.dart
@@ -14,7 +14,7 @@
/// The return values of [key] are used as the keys and the return values of
/// [value] are used as the values for the new map.
Map<K2, V2> mapMap<K1, V1, K2, V2>(Map<K1, V1> map,
- {K2 key(K1 key, V1 value), V2 value(K1 key, V1 value)}) {
+ {K2 Function(K1, V1) key, V2 Function(K1, V1) value}) {
key ??= (mapKey, _) => mapKey as K2;
value ??= (_, mapValue) => mapValue as V2;
@@ -31,7 +31,7 @@
/// select the value that goes into the resulting map based on the two original
/// values. If [value] is omitted, the value from [map2] is used.
Map<K, V> mergeMaps<K, V>(Map<K, V> map1, Map<K, V> map2,
- {V value(V value1, V value2)}) {
+ {V Function(V, V) value}) {
var result = Map<K, V>.from(map1);
if (value == null) return result..addAll(map2);
@@ -47,7 +47,7 @@
/// Returns a map from keys computed by [key] to a list of all values for which
/// [key] returns that key. The values appear in the list in the same relative
/// order as in [values].
-Map<T, List<S>> groupBy<S, T>(Iterable<S> values, T key(S element)) {
+Map<T, List<S>> groupBy<S, T>(Iterable<S> values, T Function(S) key) {
var map = <T, List<S>>{};
for (var element in values) {
var list = map.putIfAbsent(key(element), () => []);
@@ -62,8 +62,8 @@
/// The values returned by [orderBy] are compared using the [compare] function.
/// If [compare] is omitted, values must implement [Comparable<T>] and they are
/// compared using their [Comparable.compareTo].
-S minBy<S, T>(Iterable<S> values, T orderBy(S element),
- {int compare(T value1, T value2)}) {
+S minBy<S, T>(Iterable<S> values, T Function(S) orderBy,
+ {int Function(T, T) compare}) {
compare ??= defaultCompare<T>();
S minValue;
@@ -84,8 +84,8 @@
/// The values returned by [orderBy] are compared using the [compare] function.
/// If [compare] is omitted, values must implement [Comparable<T>] and they are
/// compared using their [Comparable.compareTo].
-S maxBy<S, T>(Iterable<S> values, T orderBy(S element),
- {int compare(T value1, T value2)}) {
+S maxBy<S, T>(Iterable<S> values, T Function(S) orderBy,
+ {int Function(T, T) compare}) {
compare ??= defaultCompare<T>();
S maxValue;
@@ -164,7 +164,7 @@
var lowLinks = HashMap<T, int>();
var onStack = HashSet<T>();
- strongConnect(T vertex) {
+ void strongConnect(T vertex) {
indices[vertex] = index;
lowLinks[vertex] = index;
index++;
@@ -182,7 +182,7 @@
}
if (lowLinks[vertex] == indices[vertex]) {
- var component = Set<T>();
+ var component = <T>{};
T neighbor;
do {
neighbor = stack.removeLast();
diff --git a/lib/src/iterable_zip.dart b/lib/src/iterable_zip.dart
index c2de80c..db38253 100644
--- a/lib/src/iterable_zip.dart
+++ b/lib/src/iterable_zip.dart
@@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:collection";
+import 'dart:collection';
/// Iterable that iterates over lists of values from other iterables.
///
@@ -16,10 +16,11 @@
class IterableZip<T> extends IterableBase<List<T>> {
final Iterable<Iterable<T>> _iterables;
- IterableZip(Iterable<Iterable<T>> iterables) : this._iterables = iterables;
+ IterableZip(Iterable<Iterable<T>> iterables) : _iterables = iterables;
/// Returns an iterator that combines values of the iterables' iterators
/// as long as they all have values.
+ @override
Iterator<List<T>> get iterator {
var iterators = _iterables.map((x) => x.iterator).toList(growable: false);
// TODO(lrn): Return an empty iterator directly if iterators is empty?
@@ -33,20 +34,22 @@
_IteratorZip(List<Iterator<T>> iterators) : _iterators = iterators;
+ @override
bool moveNext() {
if (_iterators.isEmpty) return false;
- for (int i = 0; i < _iterators.length; i++) {
+ for (var i = 0; i < _iterators.length; i++) {
if (!_iterators[i].moveNext()) {
_current = null;
return false;
}
}
_current = List(_iterators.length);
- for (int i = 0; i < _iterators.length; i++) {
+ for (var i = 0; i < _iterators.length; i++) {
_current[i] = _iterators[i].current;
}
return true;
}
+ @override
List<T> get current => _current;
}
diff --git a/lib/src/priority_queue.dart b/lib/src/priority_queue.dart
index ec2478b..31ff828 100644
--- a/lib/src/priority_queue.dart
+++ b/lib/src/priority_queue.dart
@@ -2,9 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:collection";
+import 'dart:collection';
-import "utils.dart";
+import 'utils.dart';
/// A priority queue is a priority based work-list of elements.
///
@@ -21,7 +21,7 @@
/// If [comparison] is omitted, it defaults to [Comparable.compare]. If this
/// is the case, `E` must implement [Comparable], and this is checked at
/// runtime for every comparison.
- factory PriorityQueue([int comparison(E e1, E e2)]) = HeapPriorityQueue<E>;
+ factory PriorityQueue([int Function(E, E) comparison]) = HeapPriorityQueue<E>;
/// Number of elements in the queue.
int get length;
@@ -144,45 +144,54 @@
/// If [comparison] is omitted, it defaults to [Comparable.compare]. If this
/// is the case, `E` must implement [Comparable], and this is checked at
/// runtime for every comparison.
- HeapPriorityQueue([int comparison(E e1, E e2)])
+ HeapPriorityQueue([int Function(E, E) comparison])
: comparison = comparison ?? defaultCompare<E>();
+ @override
void add(E element) {
_add(element);
}
+ @override
void addAll(Iterable<E> elements) {
- for (E element in elements) {
+ for (var element in elements) {
_add(element);
}
}
+ @override
void clear() {
_queue = const [];
_length = 0;
}
+ @override
bool contains(E object) {
return _locate(object) >= 0;
}
+ @override
E get first {
- if (_length == 0) throw StateError("No such element");
+ if (_length == 0) throw StateError('No such element');
return _queue[0];
}
+ @override
bool get isEmpty => _length == 0;
+ @override
bool get isNotEmpty => _length != 0;
+ @override
int get length => _length;
+ @override
bool remove(E element) {
- int index = _locate(element);
+ var index = _locate(element);
if (index < 0) return false;
- E last = _removeLast();
+ var last = _removeLast();
if (index < _length) {
- int comp = comparison(last, element);
+ var comp = comparison(last, element);
if (comp <= 0) {
_bubbleUp(last, index);
} else {
@@ -192,34 +201,39 @@
return true;
}
+ @override
Iterable<E> removeAll() {
- List<E> result = _queue;
- int length = _length;
+ var result = _queue;
+ var length = _length;
_queue = const [];
_length = 0;
return result.take(length);
}
+ @override
E removeFirst() {
- if (_length == 0) throw StateError("No such element");
- E result = _queue[0];
- E last = _removeLast();
+ if (_length == 0) throw StateError('No such element');
+ var result = _queue[0];
+ var last = _removeLast();
if (_length > 0) {
_bubbleDown(last, 0);
}
return result;
}
+ @override
List<E> toList() {
- List<E> list = List<E>()..length = _length;
- list.setRange(0, _length, _queue);
- list.sort(comparison);
+ var list = <E>[]
+ ..length = _length
+ ..setRange(0, _length, _queue)
+ ..sort(comparison);
return list;
}
+ @override
Set<E> toSet() {
Set<E> set = SplayTreeSet<E>(comparison);
- for (int i = 0; i < _length; i++) {
+ for (var i = 0; i < _length; i++) {
set.add(_queue[i]);
}
return set;
@@ -228,6 +242,7 @@
/// Returns some representation of the queue.
///
/// The format isn't significant, and may change in the future.
+ @override
String toString() {
return _queue.take(_length).toString();
}
@@ -250,19 +265,19 @@
// their left sibling is even, and the parent is found by shifting
// right by one.
// Valid range for position is [1.._length], inclusive.
- int position = 1;
+ var position = 1;
// Pre-order depth first search, omit child nodes if the current
// node has lower priority than [object], because all nodes lower
// in the heap will also have lower priority.
do {
- int index = position - 1;
- E element = _queue[index];
- int comp = comparison(element, object);
+ var index = position - 1;
+ var element = _queue[index];
+ var comp = comparison(element, object);
if (comp == 0) return index;
if (comp < 0) {
// Element may be in subtree.
// Continue with the left child, if it is there.
- int leftChildPosition = position * 2;
+ var leftChildPosition = position * 2;
if (leftChildPosition <= _length) {
position = leftChildPosition;
continue;
@@ -282,8 +297,8 @@
}
E _removeLast() {
- int newLength = _length - 1;
- E last = _queue[newLength];
+ var newLength = _length - 1;
+ var last = _queue[newLength];
_queue[newLength] = null;
_length = newLength;
return last;
@@ -296,8 +311,8 @@
/// parent, swap it with the parent.
void _bubbleUp(E element, int index) {
while (index > 0) {
- int parentIndex = (index - 1) ~/ 2;
- E parent = _queue[parentIndex];
+ var parentIndex = (index - 1) ~/ 2;
+ var parent = _queue[parentIndex];
if (comparison(element, parent) > 0) break;
_queue[index] = parent;
index = parentIndex;
@@ -311,13 +326,13 @@
/// While the `element` has lower priority than either child,
/// swap it with the highest priority child.
void _bubbleDown(E element, int index) {
- int rightChildIndex = index * 2 + 2;
+ var rightChildIndex = index * 2 + 2;
while (rightChildIndex < _length) {
- int leftChildIndex = rightChildIndex - 1;
- E leftChild = _queue[leftChildIndex];
- E rightChild = _queue[rightChildIndex];
- int comp = comparison(leftChild, rightChild);
- int minChildIndex;
+ var leftChildIndex = rightChildIndex - 1;
+ var leftChild = _queue[leftChildIndex];
+ var rightChild = _queue[rightChildIndex];
+ var comp = comparison(leftChild, rightChild);
+ var minChildIndex;
E minChild;
if (comp < 0) {
minChild = leftChild;
@@ -335,10 +350,10 @@
index = minChildIndex;
rightChildIndex = index * 2 + 2;
}
- int leftChildIndex = rightChildIndex - 1;
+ var leftChildIndex = rightChildIndex - 1;
if (leftChildIndex < _length) {
- E child = _queue[leftChildIndex];
- int comp = comparison(element, child);
+ var child = _queue[leftChildIndex];
+ var comp = comparison(element, child);
if (comp > 0) {
_queue[index] = child;
index = leftChildIndex;
@@ -351,9 +366,9 @@
///
/// Called when the list is full.
void _grow() {
- int newCapacity = _queue.length * 2 + 1;
+ var newCapacity = _queue.length * 2 + 1;
if (newCapacity < _INITIAL_CAPACITY) newCapacity = _INITIAL_CAPACITY;
- List<E> newQueue = List<E>(newCapacity);
+ var newQueue = List<E>(newCapacity);
newQueue.setRange(0, _length, _queue);
_queue = newQueue;
}
diff --git a/lib/src/queue_list.dart b/lib/src/queue_list.dart
index b2861d6..eb80cbe 100644
--- a/lib/src/queue_list.dart
+++ b/lib/src/queue_list.dart
@@ -52,8 +52,8 @@
/// Create a queue initially containing the elements of [source].
factory QueueList.from(Iterable<E> source) {
if (source is List) {
- int length = source.length;
- QueueList<E> queue = QueueList(length + 1);
+ var length = source.length;
+ var queue = QueueList<E>(length + 1);
assert(queue._table.length > length);
var sourceList = source;
queue._table.setRange(0, length, sourceList, 0);
@@ -66,15 +66,17 @@
// Collection interface.
+ @override
void add(E element) {
_add(element);
}
+ @override
void addAll(Iterable<E> iterable) {
if (iterable is List) {
var list = iterable;
- int addCount = list.length;
- int length = this.length;
+ var addCount = list.length;
+ var length = this.length;
if (length + addCount >= _table.length) {
_preGrow(length + addCount);
// After preGrow, all elements are at the start of the list.
@@ -82,19 +84,19 @@
_tail += addCount;
} else {
// Adding addCount elements won't reach _head.
- int endSpace = _table.length - _tail;
+ var endSpace = _table.length - _tail;
if (addCount < endSpace) {
_table.setRange(_tail, _tail + addCount, list, 0);
_tail += addCount;
} else {
- int preSpace = addCount - endSpace;
+ var preSpace = addCount - endSpace;
_table.setRange(_tail, _tail + endSpace, list, 0);
_table.setRange(0, preSpace, list, endSpace);
_tail = preSpace;
}
}
} else {
- for (E element in iterable) {
+ for (var element in iterable) {
_add(element);
}
}
@@ -105,44 +107,51 @@
@deprecated
QueueList<T> retype<T>() => cast<T>();
- String toString() => IterableBase.iterableToFullString(this, "{", "}");
+ @override
+ String toString() => IterableBase.iterableToFullString(this, '{', '}');
// Queue interface.
+ @override
void addLast(E element) {
_add(element);
}
+ @override
void addFirst(E element) {
_head = (_head - 1) & (_table.length - 1);
_table[_head] = element;
if (_head == _tail) _grow();
}
+ @override
E removeFirst() {
- if (_head == _tail) throw StateError("No element");
- E result = _table[_head];
+ if (_head == _tail) throw StateError('No element');
+ var result = _table[_head];
_table[_head] = null;
_head = (_head + 1) & (_table.length - 1);
return result;
}
+ @override
E removeLast() {
- if (_head == _tail) throw StateError("No element");
+ if (_head == _tail) throw StateError('No element');
_tail = (_tail - 1) & (_table.length - 1);
- E result = _table[_tail];
+ var result = _table[_tail];
_table[_tail] = null;
return result;
}
// List interface.
+ @override
int get length => (_tail - _head) & (_table.length - 1);
+ @override
set length(int value) {
- if (value < 0) throw RangeError("Length $value may not be negative.");
+ if (value < 0) throw RangeError('Length $value may not be negative.');
- int delta = value - length;
+ var delta = value - length;
if (delta >= 0) {
if (_table.length <= value) {
_preGrow(value);
@@ -151,7 +160,7 @@
return;
}
- int newTail = _tail + delta; // [delta] is negative.
+ var newTail = _tail + delta; // [delta] is negative.
if (newTail >= 0) {
_table.fillRange(newTail, _tail, null);
} else {
@@ -162,17 +171,19 @@
_tail = newTail;
}
+ @override
E operator [](int index) {
if (index < 0 || index >= length) {
- throw RangeError("Index $index must be in the range [0..$length).");
+ throw RangeError('Index $index must be in the range [0..$length).');
}
return _table[(_head + index) & (_table.length - 1)];
}
+ @override
void operator []=(int index, E value) {
if (index < 0 || index >= length) {
- throw RangeError("Index $index must be in the range [0..$length).");
+ throw RangeError('Index $index must be in the range [0..$length).');
}
_table[(_head + index) & (_table.length - 1)] = value;
@@ -194,7 +205,7 @@
assert(number > 0);
number = (number << 1) - 1;
for (;;) {
- int nextNumber = number & (number - 1);
+ var nextNumber = number & (number - 1);
if (nextNumber == 0) return number;
number = nextNumber;
}
@@ -209,8 +220,8 @@
/// Grow the table when full.
void _grow() {
- List<E> newTable = List<E>(_table.length * 2);
- int split = _table.length - _head;
+ var newTable = List<E>(_table.length * 2);
+ var split = _table.length - _head;
newTable.setRange(0, split, _table, _head);
newTable.setRange(split, split + _head, _table, 0);
_head = 0;
@@ -221,11 +232,11 @@
int _writeToList(List<E> target) {
assert(target.length >= length);
if (_head <= _tail) {
- int length = _tail - _head;
+ var length = _tail - _head;
target.setRange(0, length, _table, _head);
return length;
} else {
- int firstPartSize = _table.length - _head;
+ var firstPartSize = _table.length - _head;
target.setRange(0, firstPartSize, _table, _head);
target.setRange(firstPartSize, firstPartSize + _tail, _table, 0);
return _tail + firstPartSize;
@@ -239,8 +250,8 @@
// Add 1.5x extra room to ensure that there's room for more elements after
// expansion.
newElementCount += newElementCount >> 1;
- int newCapacity = _nextPowerOf2(newElementCount);
- List<E> newTable = List<E>(newCapacity);
+ var newCapacity = _nextPowerOf2(newElementCount);
+ var newTable = List<E>(newCapacity);
_tail = _writeToList(newTable);
_table = newTable;
_head = 0;
@@ -254,11 +265,15 @@
_table = _delegate._table.cast<T>();
}
+ @override
int get _head => _delegate._head;
+ @override
set _head(int value) => _delegate._head = value;
+ @override
int get _tail => _delegate._tail;
+ @override
set _tail(int value) => _delegate._tail = value;
}
diff --git a/lib/src/union_set.dart b/lib/src/union_set.dart
index 35ec410..09fa6cd 100644
--- a/lib/src/union_set.dart
+++ b/lib/src/union_set.dart
@@ -44,10 +44,12 @@
UnionSet.from(Iterable<Set<E>> sets, {bool disjoint = false})
: this(sets.toSet(), disjoint: disjoint);
+ @override
int get length => _disjoint
? _sets.fold(0, (length, set) => length + set.length)
: _iterable.length;
+ @override
Iterator<E> get iterator => _iterable.iterator;
/// Returns an iterable over the contents of all the sets in [this].
@@ -60,7 +62,7 @@
/// If the sets aren't guaranteed to be disjoint, this keeps track of the
/// elements we've already emitted so that we can de-duplicate them.
Iterable<E> get _dedupIterable {
- var seen = Set<E>();
+ var seen = <E>{};
return _sets.expand((set) => set).where((element) {
if (seen.contains(element)) return false;
seen.add(element);
@@ -68,8 +70,10 @@
});
}
+ @override
bool contains(Object element) => _sets.any((set) => set.contains(element));
+ @override
E lookup(Object element) {
if (element == null) return null;
@@ -78,8 +82,9 @@
.firstWhere((result) => result != null, orElse: () => null);
}
+ @override
Set<E> toSet() {
- var result = Set<E>();
+ var result = <E>{};
for (var set in _sets) {
result.addAll(set);
}
diff --git a/lib/src/union_set_controller.dart b/lib/src/union_set_controller.dart
index 8253f70..b184530 100644
--- a/lib/src/union_set_controller.dart
+++ b/lib/src/union_set_controller.dart
@@ -27,7 +27,7 @@
UnionSet<E> _set;
/// The sets whose union is exposed through [set].
- final _sets = Set<Set<E>>();
+ final _sets = <Set<E>>{};
/// Creates a set of sets that provides a view of the union of those sets.
///
diff --git a/lib/src/unmodifiable_wrappers.dart b/lib/src/unmodifiable_wrappers.dart
index 0e5c28c..ebac05f 100644
--- a/lib/src/unmodifiable_wrappers.dart
+++ b/lib/src/unmodifiable_wrappers.dart
@@ -5,7 +5,7 @@
import 'empty_unmodifiable_set.dart';
import 'wrappers.dart';
-export "dart:collection" show UnmodifiableListView, UnmodifiableMapView;
+export 'dart:collection' show UnmodifiableListView, UnmodifiableMapView;
/// A fixed-length list.
///
@@ -27,59 +27,72 @@
/// change the List's length.
abstract class NonGrowableListMixin<E> implements List<E> {
static T _throw<T>() {
- throw UnsupportedError("Cannot change the length of a fixed-length list");
+ throw UnsupportedError('Cannot change the length of a fixed-length list');
}
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
set length(int newLength) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
bool add(E value) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void addAll(Iterable<E> iterable) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void insert(int index, E element) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void insertAll(int index, Iterable<E> iterable) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
bool remove(Object value) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
E removeAt(int index) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
E removeLast() => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
- void removeWhere(bool test(E element)) => _throw();
+ @override
+ void removeWhere(bool Function(E) test) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
- void retainWhere(bool test(E element)) => _throw();
+ @override
+ void retainWhere(bool Function(E) test) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void removeRange(int start, int end) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void replaceRange(int start, int end, Iterable<E> iterable) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the length of the list are disallowed.
+ @override
void clear() => _throw();
}
@@ -105,39 +118,47 @@
/// change the Set.
abstract class UnmodifiableSetMixin<E> implements Set<E> {
static T _throw<T>() {
- throw UnsupportedError("Cannot modify an unmodifiable Set");
+ throw UnsupportedError('Cannot modify an unmodifiable Set');
}
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
bool add(E value) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
void addAll(Iterable<E> elements) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
bool remove(Object value) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
void removeAll(Iterable elements) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
void retainAll(Iterable elements) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
- void removeWhere(bool test(E element)) => _throw();
+ @override
+ void removeWhere(bool Function(E) test) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
- void retainWhere(bool test(E element)) => _throw();
+ @override
+ void retainWhere(bool Function(E) test) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the set are disallowed.
+ @override
void clear() => _throw();
}
@@ -145,27 +166,32 @@
/// change the Map.
abstract class UnmodifiableMapMixin<K, V> implements Map<K, V> {
static T _throw<T>() {
- throw UnsupportedError("Cannot modify an unmodifiable Map");
+ throw UnsupportedError('Cannot modify an unmodifiable Map');
}
/// Throws an [UnsupportedError];
/// operations that change the map are disallowed.
+ @override
void operator []=(K key, V value) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the map are disallowed.
- V putIfAbsent(K key, V ifAbsent()) => _throw();
+ @override
+ V putIfAbsent(K key, V Function() ifAbsent) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the map are disallowed.
+ @override
void addAll(Map<K, V> other) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the map are disallowed.
+ @override
V remove(Object key) => _throw();
/// Throws an [UnsupportedError];
/// operations that change the map are disallowed.
+ @override
void clear() => _throw();
/// Throws an [UnsupportedError];
diff --git a/lib/src/wrappers.dart b/lib/src/wrappers.dart
index 236a2c9..0e9e2ba 100644
--- a/lib/src/wrappers.dart
+++ b/lib/src/wrappers.dart
@@ -2,10 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:collection";
-import "dart:math" as math;
+import 'dart:collection';
+import 'dart:math' as math;
-import "unmodifiable_wrappers.dart";
+import 'unmodifiable_wrappers.dart';
typedef _KeyForValue<K, V> = K Function(V value);
@@ -18,74 +18,105 @@
const _DelegatingIterableBase();
- bool any(bool test(E element)) => _base.any(test);
+ @override
+ bool any(bool Function(E) test) => _base.any(test);
+ @override
Iterable<T> cast<T>() => _base.cast<T>();
+ @override
bool contains(Object element) => _base.contains(element);
+ @override
E elementAt(int index) => _base.elementAt(index);
- bool every(bool test(E element)) => _base.every(test);
+ @override
+ bool every(bool Function(E) test) => _base.every(test);
- Iterable<T> expand<T>(Iterable<T> f(E element)) => _base.expand(f);
+ @override
+ Iterable<T> expand<T>(Iterable<T> Function(E) f) => _base.expand(f);
+ @override
E get first => _base.first;
- E firstWhere(bool test(E element), {E orElse()}) =>
+ @override
+ E firstWhere(bool Function(E) test, {E Function() orElse}) =>
_base.firstWhere(test, orElse: orElse);
- T fold<T>(T initialValue, T combine(T previousValue, E element)) =>
+ @override
+ T fold<T>(T initialValue, T Function(T previousValue, E element) combine) =>
_base.fold(initialValue, combine);
+ @override
Iterable<E> followedBy(Iterable<E> other) => _base.followedBy(other);
- void forEach(void f(E element)) => _base.forEach(f);
+ @override
+ void forEach(void Function(E) f) => _base.forEach(f);
+ @override
bool get isEmpty => _base.isEmpty;
+ @override
bool get isNotEmpty => _base.isNotEmpty;
+ @override
Iterator<E> get iterator => _base.iterator;
- String join([String separator = ""]) => _base.join(separator);
+ @override
+ String join([String separator = '']) => _base.join(separator);
+ @override
E get last => _base.last;
- E lastWhere(bool test(E element), {E orElse()}) =>
+ @override
+ E lastWhere(bool Function(E) test, {E Function() orElse}) =>
_base.lastWhere(test, orElse: orElse);
+ @override
int get length => _base.length;
- Iterable<T> map<T>(T f(E element)) => _base.map(f);
+ @override
+ Iterable<T> map<T>(T Function(E) f) => _base.map(f);
- E reduce(E combine(E value, E element)) => _base.reduce(combine);
+ @override
+ E reduce(E Function(E value, E element) combine) => _base.reduce(combine);
@deprecated
Iterable<T> retype<T>() => cast<T>();
+ @override
E get single => _base.single;
- E singleWhere(bool test(E element), {E orElse()}) {
+ @override
+ E singleWhere(bool Function(E) test, {E Function() orElse}) {
return _base.singleWhere(test, orElse: orElse);
}
+ @override
Iterable<E> skip(int n) => _base.skip(n);
- Iterable<E> skipWhile(bool test(E value)) => _base.skipWhile(test);
+ @override
+ Iterable<E> skipWhile(bool Function(E) test) => _base.skipWhile(test);
+ @override
Iterable<E> take(int n) => _base.take(n);
- Iterable<E> takeWhile(bool test(E value)) => _base.takeWhile(test);
+ @override
+ Iterable<E> takeWhile(bool Function(E) test) => _base.takeWhile(test);
+ @override
List<E> toList({bool growable = true}) => _base.toList(growable: growable);
+ @override
Set<E> toSet() => _base.toSet();
- Iterable<E> where(bool test(E element)) => _base.where(test);
+ @override
+ Iterable<E> where(bool Function(E) test) => _base.where(test);
+ @override
Iterable<T> whereType<T>() => _base.whereType<T>();
+ @override
String toString() => _base.toString();
}
@@ -95,6 +126,7 @@
/// or it can be extended to add extra functionality on top of an existing
/// iterable object.
class DelegatingIterable<E> extends _DelegatingIterableBase<E> {
+ @override
final Iterable<E> _base;
/// Creates a wrapper that forwards operations to [base].
@@ -137,112 +169,145 @@
List<E> get _listBase => _base;
+ @override
E operator [](int index) => _listBase[index];
+ @override
void operator []=(int index, E value) {
_listBase[index] = value;
}
+ @override
List<E> operator +(List<E> other) => _listBase + other;
+ @override
void add(E value) {
_listBase.add(value);
}
+ @override
void addAll(Iterable<E> iterable) {
_listBase.addAll(iterable);
}
+ @override
Map<int, E> asMap() => _listBase.asMap();
+ @override
List<T> cast<T>() => _listBase.cast<T>();
+ @override
void clear() {
_listBase.clear();
}
+ @override
void fillRange(int start, int end, [E fillValue]) {
_listBase.fillRange(start, end, fillValue);
}
+ @override
set first(E value) {
- if (this.isEmpty) throw RangeError.index(0, this);
+ if (isEmpty) throw RangeError.index(0, this);
this[0] = value;
}
+ @override
Iterable<E> getRange(int start, int end) => _listBase.getRange(start, end);
+ @override
int indexOf(E element, [int start = 0]) => _listBase.indexOf(element, start);
- int indexWhere(bool test(E element), [int start = 0]) =>
+ @override
+ int indexWhere(bool Function(E) test, [int start = 0]) =>
_listBase.indexWhere(test, start);
+ @override
void insert(int index, E element) {
_listBase.insert(index, element);
}
- insertAll(int index, Iterable<E> iterable) {
+ @override
+ void insertAll(int index, Iterable<E> iterable) {
_listBase.insertAll(index, iterable);
}
+ @override
set last(E value) {
- if (this.isEmpty) throw RangeError.index(0, this);
- this[this.length - 1] = value;
+ if (isEmpty) throw RangeError.index(0, this);
+ this[length - 1] = value;
}
+ @override
int lastIndexOf(E element, [int start]) =>
_listBase.lastIndexOf(element, start);
- int lastIndexWhere(bool test(E element), [int start]) =>
+ @override
+ int lastIndexWhere(bool Function(E) test, [int start]) =>
_listBase.lastIndexWhere(test, start);
+ @override
set length(int newLength) {
_listBase.length = newLength;
}
+ @override
bool remove(Object value) => _listBase.remove(value);
+ @override
E removeAt(int index) => _listBase.removeAt(index);
+ @override
E removeLast() => _listBase.removeLast();
+ @override
void removeRange(int start, int end) {
_listBase.removeRange(start, end);
}
- void removeWhere(bool test(E element)) {
+ @override
+ void removeWhere(bool Function(E) test) {
_listBase.removeWhere(test);
}
+ @override
void replaceRange(int start, int end, Iterable<E> iterable) {
_listBase.replaceRange(start, end, iterable);
}
- void retainWhere(bool test(E element)) {
+ @override
+ void retainWhere(bool Function(E) test) {
_listBase.retainWhere(test);
}
@deprecated
+ @override
List<T> retype<T>() => cast<T>();
+ @override
Iterable<E> get reversed => _listBase.reversed;
+ @override
void setAll(int index, Iterable<E> iterable) {
_listBase.setAll(index, iterable);
}
+ @override
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) {
_listBase.setRange(start, end, iterable, skipCount);
}
+ @override
void shuffle([math.Random random]) {
_listBase.shuffle(random);
}
- void sort([int compare(E a, E b)]) {
+ @override
+ void sort([int Function(E, E) compare]) {
_listBase.sort(compare);
}
+ @override
List<E> sublist(int start, [int end]) => _listBase.sublist(start, end);
}
@@ -269,49 +334,65 @@
Set<E> get _setBase => _base;
+ @override
bool add(E value) => _setBase.add(value);
+ @override
void addAll(Iterable<E> elements) {
_setBase.addAll(elements);
}
+ @override
Set<T> cast<T>() => _setBase.cast<T>();
+ @override
void clear() {
_setBase.clear();
}
+ @override
bool containsAll(Iterable<Object> other) => _setBase.containsAll(other);
+ @override
Set<E> difference(Set<Object> other) => _setBase.difference(other);
+ @override
Set<E> intersection(Set<Object> other) => _setBase.intersection(other);
+ @override
E lookup(Object element) => _setBase.lookup(element);
+ @override
bool remove(Object value) => _setBase.remove(value);
+ @override
void removeAll(Iterable<Object> elements) {
_setBase.removeAll(elements);
}
- void removeWhere(bool test(E element)) {
+ @override
+ void removeWhere(bool Function(E) test) {
_setBase.removeWhere(test);
}
+ @override
void retainAll(Iterable<Object> elements) {
_setBase.retainAll(elements);
}
@deprecated
+ @override
Set<T> retype<T>() => cast<T>();
- void retainWhere(bool test(E element)) {
+ @override
+ void retainWhere(bool Function(E) test) {
_setBase.retainWhere(test);
}
+ @override
Set<E> union(Set<E> other) => _setBase.union(other);
+ @override
Set<E> toSet() => DelegatingSet<E>(_setBase.toSet());
}
@@ -339,43 +420,55 @@
Queue<E> get _baseQueue => _base;
+ @override
void add(E value) {
_baseQueue.add(value);
}
+ @override
void addAll(Iterable<E> iterable) {
_baseQueue.addAll(iterable);
}
+ @override
void addFirst(E value) {
_baseQueue.addFirst(value);
}
+ @override
void addLast(E value) {
_baseQueue.addLast(value);
}
+ @override
Queue<T> cast<T>() => _baseQueue.cast<T>();
+ @override
void clear() {
_baseQueue.clear();
}
+ @override
bool remove(Object object) => _baseQueue.remove(object);
- void removeWhere(bool test(E element)) {
+ @override
+ void removeWhere(bool Function(E) test) {
_baseQueue.removeWhere(test);
}
- void retainWhere(bool test(E element)) {
+ @override
+ void retainWhere(bool Function(E) test) {
_baseQueue.retainWhere(test);
}
@deprecated
+ @override
Queue<T> retype<T>() => cast<T>();
+ @override
E removeFirst() => _baseQueue.removeFirst();
+ @override
E removeLast() => _baseQueue.removeLast();
}
@@ -403,64 +496,87 @@
@Deprecated('Use map.cast<K, V> instead.')
static Map<K, V> typed<K, V>(Map base) => base.cast<K, V>();
+ @override
V operator [](Object key) => _base[key];
+ @override
void operator []=(K key, V value) {
_base[key] = value;
}
+ @override
void addAll(Map<K, V> other) {
_base.addAll(other);
}
+ @override
void addEntries(Iterable<MapEntry<K, V>> entries) {
_base.addEntries(entries);
}
+ @override
void clear() {
_base.clear();
}
+ @override
Map<K2, V2> cast<K2, V2>() => _base.cast<K2, V2>();
+ @override
bool containsKey(Object key) => _base.containsKey(key);
+ @override
bool containsValue(Object value) => _base.containsValue(value);
+ @override
Iterable<MapEntry<K, V>> get entries => _base.entries;
- void forEach(void f(K key, V value)) {
+ @override
+ void forEach(void Function(K, V) f) {
_base.forEach(f);
}
+ @override
bool get isEmpty => _base.isEmpty;
+ @override
bool get isNotEmpty => _base.isNotEmpty;
+ @override
Iterable<K> get keys => _base.keys;
+ @override
int get length => _base.length;
- Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> transform(K key, V value)) =>
+ @override
+ Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> Function(K, V) transform) =>
_base.map(transform);
- V putIfAbsent(K key, V ifAbsent()) => _base.putIfAbsent(key, ifAbsent);
+ @override
+ V putIfAbsent(K key, V Function() ifAbsent) =>
+ _base.putIfAbsent(key, ifAbsent);
+ @override
V remove(Object key) => _base.remove(key);
- void removeWhere(bool test(K key, V value)) => _base.removeWhere(test);
+ @override
+ void removeWhere(bool Function(K, V) test) => _base.removeWhere(test);
@deprecated
Map<K2, V2> retype<K2, V2>() => cast<K2, V2>();
+ @override
Iterable<V> get values => _base.values;
+ @override
String toString() => _base.toString();
- V update(K key, V update(V value), {V ifAbsent()}) =>
+ @override
+ V update(K key, V Function(V) update, {V Function() ifAbsent}) =>
_base.update(key, update, ifAbsent: ifAbsent);
- void updateAll(V update(K key, V value)) => _base.updateAll(update);
+ @override
+ void updateAll(V Function(K, V) update) => _base.updateAll(update);
}
/// An unmodifiable [Set] view of the keys of a [Map].
@@ -478,8 +594,10 @@
MapKeySet(Map<E, dynamic> base) : _baseMap = base;
+ @override
Iterable<E> get _base => _baseMap.keys;
+ @override
Set<T> cast<T>() {
if (this is MapKeySet<T>) {
return this as MapKeySet<T>;
@@ -487,16 +605,22 @@
return Set.castFrom<E, T>(this);
}
+ @override
bool contains(Object element) => _baseMap.containsKey(element);
+ @override
bool get isEmpty => _baseMap.isEmpty;
+ @override
bool get isNotEmpty => _baseMap.isNotEmpty;
+ @override
int get length => _baseMap.length;
+ @override
String toString() => "{${_base.join(', ')}}";
+ @override
bool containsAll(Iterable<Object> other) => other.every(contains);
/// Returns a new set with the the elements of [this] that are not in [other].
@@ -506,6 +630,7 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<E> difference(Set<Object> other) =>
where((element) => !other.contains(element)).toSet();
@@ -516,14 +641,17 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<E> intersection(Set<Object> other) => where(other.contains).toSet();
/// Throws an [UnsupportedError] since there's no corresponding method for
/// [Map]s.
+ @override
E lookup(Object element) =>
throw UnsupportedError("MapKeySet doesn't support lookup().");
@deprecated
+ @override
Set<T> retype<T>() => Set.castFrom<E, T>(this);
/// Returns a new set which contains all the elements of [this] and [other].
@@ -533,6 +661,7 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<E> union(Set<E> other) => toSet()..addAll(other);
}
@@ -566,12 +695,14 @@
/// [keyForValue] returns the key in the map that should be associated with
/// the given value. The set's notion of equality is identical to the equality
/// of the return values of [keyForValue].
- MapValueSet(Map<K, V> base, K keyForValue(V value))
+ MapValueSet(Map<K, V> base, K Function(V) keyForValue)
: _baseMap = base,
_keyForValue = keyForValue;
+ @override
Iterable<V> get _base => _baseMap.values;
+ @override
Set<T> cast<T>() {
if (this is Set<T>) {
return this as Set<T>;
@@ -579,6 +710,7 @@
return Set.castFrom<V, T>(this);
}
+ @override
bool contains(Object element) {
if (element != null && element is! V) return false;
var key = _keyForValue(element as V);
@@ -586,17 +718,22 @@
return _baseMap.containsKey(key);
}
+ @override
bool get isEmpty => _baseMap.isEmpty;
+ @override
bool get isNotEmpty => _baseMap.isNotEmpty;
+ @override
int get length => _baseMap.length;
+ @override
String toString() => toSet().toString();
+ @override
bool add(V value) {
- K key = _keyForValue(value);
- bool result = false;
+ var key = _keyForValue(value);
+ var result = false;
_baseMap.putIfAbsent(key, () {
result = true;
return value;
@@ -604,10 +741,13 @@
return result;
}
+ @override
void addAll(Iterable<V> elements) => elements.forEach(add);
+ @override
void clear() => _baseMap.clear();
+ @override
bool containsAll(Iterable<Object> other) => other.every(contains);
/// Returns a new set with the the elements of [this] that are not in [other].
@@ -617,6 +757,7 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<V> difference(Set<Object> other) =>
where((element) => !other.contains(element)).toSet();
@@ -627,8 +768,10 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<V> intersection(Set<Object> other) => where(other.contains).toSet();
+ @override
V lookup(Object element) {
if (element != null && element is! V) return null;
var key = _keyForValue(element as V);
@@ -636,6 +779,7 @@
return _baseMap[key];
}
+ @override
bool remove(Object element) {
if (element != null && element is! V) return false;
var key = _keyForValue(element as V);
@@ -645,9 +789,11 @@
return true;
}
+ @override
void removeAll(Iterable<Object> elements) => elements.forEach(remove);
- void removeWhere(bool test(V element)) {
+ @override
+ void removeWhere(bool Function(V) test) {
var toRemove = [];
_baseMap.forEach((key, value) {
if (test(value)) toRemove.add(key);
@@ -655,6 +801,7 @@
toRemove.forEach(_baseMap.remove);
}
+ @override
void retainAll(Iterable<Object> elements) {
var valuesToRetain = Set<V>.identity();
for (var element in elements) {
@@ -672,10 +819,12 @@
keysToRemove.forEach(_baseMap.remove);
}
- void retainWhere(bool test(V element)) =>
+ @override
+ void retainWhere(bool Function(V) test) =>
removeWhere((element) => !test(element));
@deprecated
+ @override
Set<T> retype<T>() => Set.castFrom<V, T>(this);
/// Returns a new set which contains all the elements of [this] and [other].
@@ -685,5 +834,6 @@
///
/// Note that the returned set will use the default equality operation, which
/// may be different than the equality operation [this] uses.
+ @override
Set<V> union(Set<V> other) => toSet()..addAll(other);
}
diff --git a/lib/wrappers.dart b/lib/wrappers.dart
index 13031f5..d3a2ff6 100644
--- a/lib/wrappers.dart
+++ b/lib/wrappers.dart
@@ -3,9 +3,9 @@
// BSD-style license that can be found in the LICENSE file.
/// Import `collection.dart` instead.
-@Deprecated("Will be removed in collection 2.0.0.")
+@Deprecated('Will be removed in collection 2.0.0.')
library dart.pkg.collection.wrappers;
-export "src/canonicalized_map.dart";
-export "src/unmodifiable_wrappers.dart";
-export "src/wrappers.dart";
+export 'src/canonicalized_map.dart';
+export 'src/unmodifiable_wrappers.dart';
+export 'src/wrappers.dart';
diff --git a/pubspec.yaml b/pubspec.yaml
index 95759b8..48413da 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,12 +1,12 @@
name: collection
-version: 1.14.12
+version: 1.14.13-dev
description: Collections and utilities functions and classes related to collections.
author: Dart Team <misc@dartlang.org>
homepage: https://www.github.com/dart-lang/collection
environment:
- sdk: '>=2.0.0 <3.0.0'
+ sdk: '>=2.3.0 <3.0.0'
dev_dependencies:
pedantic: ^1.0.0
diff --git a/test/algorithms_test.dart b/test/algorithms_test.dart
index 0ae0916..0d0d414 100644
--- a/test/algorithms_test.dart
+++ b/test/algorithms_test.dart
@@ -5,32 +5,32 @@
/// Tests algorithm utilities.
import 'dart:math';
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
void main() {
void testShuffle(List list) {
- List copy = list.toList();
+ var copy = list.toList();
shuffle(list);
expect(UnorderedIterableEquality().equals(list, copy), isTrue);
}
- test("Shuffle 0", () {
+ test('Shuffle 0', () {
testShuffle([]);
});
- test("Shuffle 1", () {
+ test('Shuffle 1', () {
testShuffle([1]);
});
- test("Shuffle 3", () {
+ test('Shuffle 3', () {
testShuffle([1, 2, 3]);
});
- test("Shuffle 10", () {
+ test('Shuffle 10', () {
testShuffle([1, 2, 3, 4, 5, 1, 3, 5, 7, 9]);
});
- test("Shuffle shuffles", () {
- List l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
- List c = l.toList();
- int count = 0;
+ test('Shuffle shuffles', () {
+ var l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ var c = l.toList();
+ var count = 0;
do {
shuffle(l);
if (!const ListEquality().equals(c, l)) return;
@@ -39,13 +39,13 @@
// same result every time is disappearingly tiny.
count++;
// If this happens even once, it's ok to report it.
- print("Failed shuffle $count times");
+ print('Failed shuffle $count times');
if (count == 10) fail("Shuffle didn't change order.");
} while (true);
});
- test("Shuffle sublist", () {
- List l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
- List c = l.toList();
+ test('Shuffle sublist', () {
+ var l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
+ var c = l.toList();
shuffle(l, 4, 12);
expect(const IterableEquality().equals(l.getRange(0, 4), c.getRange(0, 4)),
isTrue);
@@ -58,17 +58,17 @@
isTrue);
});
- test("binsearch0", () {
+ test('binsearch0', () {
expect(binarySearch([], 2), equals(-1));
});
- test("binsearch1", () {
+ test('binsearch1', () {
expect(binarySearch([5], 2), equals(-1));
expect(binarySearch([5], 5), equals(0));
expect(binarySearch([5], 7), equals(-1));
});
- test("binsearch3", () {
+ test('binsearch3', () {
expect(binarySearch([0, 5, 10], -1), equals(-1));
expect(binarySearch([0, 5, 10], 0), equals(0));
expect(binarySearch([0, 5, 10], 2), equals(-1));
@@ -78,18 +78,18 @@
expect(binarySearch([0, 5, 10], 12), equals(-1));
});
- test("binsearchCompare0", () {
+ test('binsearchCompare0', () {
expect(binarySearch(<C>[], C(2), compare: compareC), equals(-1));
});
- test("binsearchCompare1", () {
+ test('binsearchCompare1', () {
var l1 = [C(5)];
expect(binarySearch(l1, C(2), compare: compareC), equals(-1));
expect(binarySearch(l1, C(5), compare: compareC), equals(0));
expect(binarySearch(l1, C(7), compare: compareC), equals(-1));
});
- test("binsearchCompare3", () {
+ test('binsearchCompare3', () {
var l3 = [C(0), C(5), C(10)];
expect(binarySearch(l3, C(-1), compare: compareC), equals(-1));
expect(binarySearch(l3, C(0), compare: compareC), equals(0));
@@ -100,17 +100,17 @@
expect(binarySearch(l3, C(12), compare: compareC), equals(-1));
});
- test("lowerbound0", () {
+ test('lowerbound0', () {
expect(lowerBound([], 2), equals(0));
});
- test("lowerbound1", () {
+ test('lowerbound1', () {
expect(lowerBound([5], 2), equals(0));
expect(lowerBound([5], 5), equals(0));
expect(lowerBound([5], 7), equals(1));
});
- test("lowerbound3", () {
+ test('lowerbound3', () {
expect(lowerBound([0, 5, 10], -1), equals(0));
expect(lowerBound([0, 5, 10], 0), equals(0));
expect(lowerBound([0, 5, 10], 2), equals(1));
@@ -120,23 +120,23 @@
expect(lowerBound([0, 5, 10], 12), equals(3));
});
- test("lowerboundRepeat", () {
+ test('lowerboundRepeat', () {
expect(lowerBound([5, 5, 5], 5), equals(0));
expect(lowerBound([0, 5, 5, 5, 10], 5), equals(1));
});
- test("lowerboundCompare0", () {
+ test('lowerboundCompare0', () {
expect(lowerBound(<C>[], C(2), compare: compareC), equals(0));
});
- test("lowerboundCompare1", () {
+ test('lowerboundCompare1', () {
var l1 = [C(5)];
expect(lowerBound(l1, C(2), compare: compareC), equals(0));
expect(lowerBound(l1, C(5), compare: compareC), equals(0));
expect(lowerBound(l1, C(7), compare: compareC), equals(1));
});
- test("lowerboundCompare3", () {
+ test('lowerboundCompare3', () {
var l3 = [C(0), C(5), C(10)];
expect(lowerBound(l3, C(-1), compare: compareC), equals(0));
expect(lowerBound(l3, C(0), compare: compareC), equals(0));
@@ -147,29 +147,29 @@
expect(lowerBound(l3, C(12), compare: compareC), equals(3));
});
- test("lowerboundCompareRepeat", () {
+ test('lowerboundCompareRepeat', () {
var l1 = [C(5), C(5), C(5)];
var l2 = [C(0), C(5), C(5), C(5), C(10)];
expect(lowerBound(l1, C(5), compare: compareC), equals(0));
expect(lowerBound(l2, C(5), compare: compareC), equals(1));
});
- test("insertionSortRandom", () {
- Random random = Random();
- for (int i = 0; i < 25; i++) {
- List list = List(i);
- for (int j = 0; j < i; j++) {
+ test('insertionSortRandom', () {
+ var random = Random();
+ for (var i = 0; i < 25; i++) {
+ var list = List(i);
+ for (var j = 0; j < i; j++) {
list[j] = random.nextInt(25); // Expect some equal elements.
}
insertionSort(list);
- for (int j = 1; j < i; j++) {
+ for (var j = 1; j < i; j++) {
expect(list[j - 1], lessThanOrEqualTo(list[j]));
}
}
});
- test("insertionSortSubRanges", () {
- List l = [6, 5, 4, 3, 2, 1];
+ test('insertionSortSubRanges', () {
+ var l = [6, 5, 4, 3, 2, 1];
insertionSort(l, start: 2, end: 4);
expect(l, equals([6, 5, 3, 4, 2, 1]));
insertionSort(l, start: 1, end: 1);
@@ -182,8 +182,8 @@
expect(l, equals([1, 2, 3, 4, 5, 6]));
});
- test("insertionSortSpecialCases", () {
- List l = [6, 6, 6, 6, 6, 6];
+ test('insertionSortSpecialCases', () {
+ var l = [6, 6, 6, 6, 6, 6];
insertionSort(l);
expect(l, equals([6, 6, 6, 6, 6, 6]));
@@ -192,38 +192,38 @@
expect(l, equals([0, 0, 3, 3, 6, 6]));
});
- test("MergeSortRandom", () {
- Random random = Random();
- for (int i = 0; i < 250; i += 1) {
- List list = List(i);
- for (int j = 0; j < i; j++) {
+ test('MergeSortRandom', () {
+ var random = Random();
+ for (var i = 0; i < 250; i += 1) {
+ var list = List(i);
+ for (var j = 0; j < i; j++) {
list[j] = random.nextInt(i); // Expect some equal elements.
}
mergeSort(list);
- for (int j = 1; j < i; j++) {
+ for (var j = 1; j < i; j++) {
expect(list[j - 1], lessThanOrEqualTo(list[j]));
}
}
});
- test("MergeSortPreservesOrder", () {
- Random random = Random();
+ test('MergeSortPreservesOrder', () {
+ var random = Random();
// Small case where only insertion call is called,
// larger case where the internal moving insertion sort is used
// larger cases with multiple splittings, numbers just around a power of 2.
- for (int size in [8, 50, 511, 512, 513]) {
+ for (var size in [8, 50, 511, 512, 513]) {
var list = List<OC>(size);
// Class OC compares using id.
// With size elements with id's in the range 0..size/4, a number of
- // collisions are guaranteed. These should be sorted so that the "order"
+ // collisions are guaranteed. These should be sorted so that the 'order'
// part of the objects are still in order.
- for (int i = 0; i < size; i++) {
+ for (var i = 0; i < size; i++) {
list[i] = OC(random.nextInt(size >> 2), i);
}
mergeSort(list);
- OC prev = list[0];
- for (int i = 1; i < size; i++) {
- OC next = list[i];
+ var prev = list[0];
+ for (var i = 1; i < size; i++) {
+ var next = list[i];
expect(prev.id, lessThanOrEqualTo(next.id));
if (next.id == prev.id) {
expect(prev.order, lessThanOrEqualTo(next.order));
@@ -232,13 +232,13 @@
}
// Reverse compare on part of list.
List copy = list.toList();
- int min = size >> 2;
- int max = size - min;
+ var min = size >> 2;
+ var max = size - min;
mergeSort<OC>(list,
start: min, end: max, compare: (a, b) => b.compareTo(a));
prev = list[min];
- for (int i = min + 1; i < max; i++) {
- OC next = list[i];
+ for (var i = min + 1; i < max; i++) {
+ var next = list[i];
expect(prev.id, greaterThanOrEqualTo(next.id));
if (next.id == prev.id) {
expect(prev.order, lessThanOrEqualTo(next.order));
@@ -252,53 +252,53 @@
}
});
- test("MergeSortSpecialCases", () {
- for (int size in [511, 512, 513]) {
+ test('MergeSortSpecialCases', () {
+ for (var size in [511, 512, 513]) {
// All equal.
- List list = List(size);
- for (int i = 0; i < size; i++) {
+ var list = List(size);
+ for (var i = 0; i < size; i++) {
list[i] = OC(0, i);
}
mergeSort(list);
- for (int i = 0; i < size; i++) {
+ for (var i = 0; i < size; i++) {
expect(list[i].order, equals(i));
}
// All but one equal, first.
list[0] = OC(1, 0);
- for (int i = 1; i < size; i++) {
+ for (var i = 1; i < size; i++) {
list[i] = OC(0, i);
}
mergeSort(list);
- for (int i = 0; i < size - 1; i++) {
+ for (var i = 0; i < size - 1; i++) {
expect(list[i].order, equals(i + 1));
}
expect(list[size - 1].order, equals(0));
// All but one equal, last.
- for (int i = 0; i < size - 1; i++) {
+ for (var i = 0; i < size - 1; i++) {
list[i] = OC(0, i);
}
list[size - 1] = OC(-1, size - 1);
mergeSort(list);
expect(list[0].order, equals(size - 1));
- for (int i = 1; i < size; i++) {
+ for (var i = 1; i < size; i++) {
expect(list[i].order, equals(i - 1));
}
// Reversed.
- for (int i = 0; i < size; i++) {
+ for (var i = 0; i < size; i++) {
list[i] = OC(size - 1 - i, i);
}
mergeSort(list);
- for (int i = 0; i < size; i++) {
+ for (var i = 0; i < size; i++) {
expect(list[i].id, equals(i));
expect(list[i].order, equals(size - 1 - i));
}
}
});
- test("Reverse", () {
- List l = [6, 5, 4, 3, 2, 1];
+ test('Reverse', () {
+ var l = [6, 5, 4, 3, 2, 1];
reverse(l, 2, 4);
expect(l, equals([6, 5, 3, 4, 2, 1]));
reverse(l, 1, 1);
@@ -323,6 +323,8 @@
final int id;
final int order;
OC(this.id, this.order);
+ @override
int compareTo(OC other) => id - other.id;
- String toString() => "OC[$id,$order]";
+ @override
+ String toString() => 'OC[$id,$order]';
}
diff --git a/test/canonicalized_map_test.dart b/test/canonicalized_map_test.dart
index 4ec0054..2d42b09 100644
--- a/test/canonicalized_map_test.dart
+++ b/test/canonicalized_map_test.dart
@@ -2,207 +2,207 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
void main() {
- group("with an empty canonicalized map", () {
+ group('with an empty canonicalized map', () {
CanonicalizedMap<int, String, String> map;
setUp(() {
map = CanonicalizedMap(int.parse,
- isValidKey: (s) => RegExp(r"^\d+$").hasMatch(s as String));
+ isValidKey: (s) => RegExp(r'^\d+$').hasMatch(s as String));
});
- test("canonicalizes keys on set and get", () {
- map["1"] = "value";
- expect(map["01"], equals("value"));
+ test('canonicalizes keys on set and get', () {
+ map['1'] = 'value';
+ expect(map['01'], equals('value'));
});
- test("get returns null for uncanonicalizable key", () {
- expect(map["foo"], isNull);
+ test('get returns null for uncanonicalizable key', () {
+ expect(map['foo'], isNull);
});
- test("set affects nothing for uncanonicalizable key", () {
- map["foo"] = "value";
- expect(map["foo"], isNull);
- expect(map.containsKey("foo"), isFalse);
+ test('set affects nothing for uncanonicalizable key', () {
+ map['foo'] = 'value';
+ expect(map['foo'], isNull);
+ expect(map.containsKey('foo'), isFalse);
expect(map.length, equals(0));
});
- test("canonicalizes keys for addAll", () {
- map.addAll({"1": "value 1", "2": "value 2", "3": "value 3"});
- expect(map["01"], equals("value 1"));
- expect(map["02"], equals("value 2"));
- expect(map["03"], equals("value 3"));
+ test('canonicalizes keys for addAll', () {
+ map.addAll({'1': 'value 1', '2': 'value 2', '3': 'value 3'});
+ expect(map['01'], equals('value 1'));
+ expect(map['02'], equals('value 2'));
+ expect(map['03'], equals('value 3'));
});
- test("uses the final value for addAll collisions", () {
- map.addAll({"1": "value 1", "01": "value 2", "001": "value 3"});
+ test('uses the final value for addAll collisions', () {
+ map.addAll({'1': 'value 1', '01': 'value 2', '001': 'value 3'});
expect(map.length, equals(1));
- expect(map["0001"], equals("value 3"));
+ expect(map['0001'], equals('value 3'));
});
- test("clear clears the map", () {
- map.addAll({"1": "value 1", "2": "value 2", "3": "value 3"});
+ test('clear clears the map', () {
+ map.addAll({'1': 'value 1', '2': 'value 2', '3': 'value 3'});
expect(map, isNot(isEmpty));
map.clear();
expect(map, isEmpty);
});
- test("canonicalizes keys for containsKey", () {
- map["1"] = "value";
- expect(map.containsKey("01"), isTrue);
- expect(map.containsKey("2"), isFalse);
+ test('canonicalizes keys for containsKey', () {
+ map['1'] = 'value';
+ expect(map.containsKey('01'), isTrue);
+ expect(map.containsKey('2'), isFalse);
});
- test("containsKey returns false for uncanonicalizable key", () {
- expect(map.containsKey("foo"), isFalse);
+ test('containsKey returns false for uncanonicalizable key', () {
+ expect(map.containsKey('foo'), isFalse);
});
- test("canonicalizes keys for putIfAbsent", () {
- map["1"] = "value";
- expect(map.putIfAbsent("01", () => throw Exception("shouldn't run")),
- equals("value"));
- expect(map.putIfAbsent("2", () => "new value"), equals("new value"));
+ test('canonicalizes keys for putIfAbsent', () {
+ map['1'] = 'value';
+ expect(map.putIfAbsent('01', () => throw Exception("shouldn't run")),
+ equals('value'));
+ expect(map.putIfAbsent('2', () => 'new value'), equals('new value'));
});
- test("canonicalizes keys for remove", () {
- map["1"] = "value";
- expect(map.remove("2"), isNull);
- expect(map.remove("01"), equals("value"));
+ test('canonicalizes keys for remove', () {
+ map['1'] = 'value';
+ expect(map.remove('2'), isNull);
+ expect(map.remove('01'), equals('value'));
expect(map, isEmpty);
});
- test("remove returns null for uncanonicalizable key", () {
- expect(map.remove("foo"), isNull);
+ test('remove returns null for uncanonicalizable key', () {
+ expect(map.remove('foo'), isNull);
});
- test("containsValue returns whether a value is in the map", () {
- map["1"] = "value";
- expect(map.containsValue("value"), isTrue);
- expect(map.containsValue("not value"), isFalse);
+ test('containsValue returns whether a value is in the map', () {
+ map['1'] = 'value';
+ expect(map.containsValue('value'), isTrue);
+ expect(map.containsValue('not value'), isFalse);
});
- test("isEmpty returns whether the map is empty", () {
+ test('isEmpty returns whether the map is empty', () {
expect(map.isEmpty, isTrue);
- map["1"] = "value";
+ map['1'] = 'value';
expect(map.isEmpty, isFalse);
- map.remove("01");
+ map.remove('01');
expect(map.isEmpty, isTrue);
});
test("isNotEmpty returns whether the map isn't empty", () {
expect(map.isNotEmpty, isFalse);
- map["1"] = "value";
+ map['1'] = 'value';
expect(map.isNotEmpty, isTrue);
- map.remove("01");
+ map.remove('01');
expect(map.isNotEmpty, isFalse);
});
- test("length returns the number of pairs in the map", () {
+ test('length returns the number of pairs in the map', () {
expect(map.length, equals(0));
- map["1"] = "value 1";
+ map['1'] = 'value 1';
expect(map.length, equals(1));
- map["01"] = "value 01";
+ map['01'] = 'value 01';
expect(map.length, equals(1));
- map["02"] = "value 02";
+ map['02'] = 'value 02';
expect(map.length, equals(2));
});
- test("uses original keys for keys", () {
- map["001"] = "value 1";
- map["02"] = "value 2";
- expect(map.keys, equals(["001", "02"]));
+ test('uses original keys for keys', () {
+ map['001'] = 'value 1';
+ map['02'] = 'value 2';
+ expect(map.keys, equals(['001', '02']));
});
- test("uses original keys for forEach", () {
- map["001"] = "value 1";
- map["02"] = "value 2";
+ test('uses original keys for forEach', () {
+ map['001'] = 'value 1';
+ map['02'] = 'value 2';
var keys = [];
map.forEach((key, value) => keys.add(key));
- expect(keys, equals(["001", "02"]));
+ expect(keys, equals(['001', '02']));
});
- test("values returns all values in the map", () {
+ test('values returns all values in the map', () {
map.addAll(
- {"1": "value 1", "01": "value 01", "2": "value 2", "03": "value 03"});
+ {'1': 'value 1', '01': 'value 01', '2': 'value 2', '03': 'value 03'});
- expect(map.values, equals(["value 01", "value 2", "value 03"]));
+ expect(map.values, equals(['value 01', 'value 2', 'value 03']));
});
- test("entries returns all key-value pairs in the map", () {
+ test('entries returns all key-value pairs in the map', () {
map.addAll({
- "1": "value 1",
- "01": "value 01",
- "2": "value 2",
+ '1': 'value 1',
+ '01': 'value 01',
+ '2': 'value 2',
});
var entries = map.entries.toList();
- expect(entries[0].key, "01");
- expect(entries[0].value, "value 01");
- expect(entries[1].key, "2");
- expect(entries[1].value, "value 2");
+ expect(entries[0].key, '01');
+ expect(entries[0].value, 'value 01');
+ expect(entries[1].key, '2');
+ expect(entries[1].value, 'value 2');
});
- test("addEntries adds key-value pairs to the map", () {
+ test('addEntries adds key-value pairs to the map', () {
map.addEntries([
- MapEntry("1", "value 1"),
- MapEntry("01", "value 01"),
- MapEntry("2", "value 2"),
+ MapEntry('1', 'value 1'),
+ MapEntry('01', 'value 01'),
+ MapEntry('2', 'value 2'),
]);
- expect(map, {"01": "value 01", "2": "value 2"});
+ expect(map, {'01': 'value 01', '2': 'value 2'});
});
- test("cast returns a new map instance", () {
+ test('cast returns a new map instance', () {
expect(map.cast<Pattern, Pattern>(), isNot(same(map)));
});
});
- group("CanonicalizedMap builds an informative string representation", () {
+ group('CanonicalizedMap builds an informative string representation', () {
var map;
setUp(() {
map = CanonicalizedMap<int, String, dynamic>(int.parse,
- isValidKey: (s) => RegExp(r"^\d+$").hasMatch(s as String));
+ isValidKey: (s) => RegExp(r'^\d+$').hasMatch(s as String));
});
- test("for an empty map", () {
+ test('for an empty map', () {
expect(map.toString(), equals('{}'));
});
- test("for a map with one value", () {
- map.addAll({"1": "value 1"});
+ test('for a map with one value', () {
+ map.addAll({'1': 'value 1'});
expect(map.toString(), equals('{1: value 1}'));
});
- test("for a map with multiple values", () {
+ test('for a map with multiple values', () {
map.addAll(
- {"1": "value 1", "01": "value 01", "2": "value 2", "03": "value 03"});
+ {'1': 'value 1', '01': 'value 01', '2': 'value 2', '03': 'value 03'});
expect(
map.toString(), equals('{01: value 01, 2: value 2, 03: value 03}'));
});
- test("for a map with a loop", () {
- map.addAll({"1": "value 1", "2": map});
+ test('for a map with a loop', () {
+ map.addAll({'1': 'value 1', '2': map});
expect(map.toString(), equals('{1: value 1, 2: {...}}'));
});
});
- group("CanonicalizedMap.from", () {
- test("canonicalizes its keys", () {
+ group('CanonicalizedMap.from', () {
+ test('canonicalizes its keys', () {
var map = CanonicalizedMap.from(
- {"1": "value 1", "2": "value 2", "3": "value 3"}, int.parse);
- expect(map["01"], equals("value 1"));
- expect(map["02"], equals("value 2"));
- expect(map["03"], equals("value 3"));
+ {'1': 'value 1', '2': 'value 2', '3': 'value 3'}, int.parse);
+ expect(map['01'], equals('value 1'));
+ expect(map['02'], equals('value 2'));
+ expect(map['03'], equals('value 3'));
});
- test("uses the final value for collisions", () {
+ test('uses the final value for collisions', () {
var map = CanonicalizedMap.from(
- {"1": "value 1", "01": "value 2", "001": "value 3"}, int.parse);
+ {'1': 'value 1', '01': 'value 2', '001': 'value 3'}, int.parse);
expect(map.length, equals(1));
- expect(map["0001"], equals("value 3"));
+ expect(map['0001'], equals('value 3'));
});
});
}
diff --git a/test/combined_wrapper/list_test.dart b/test/combined_wrapper/list_test.dart
index 5bb0cb1..2705e39 100644
--- a/test/combined_wrapper/list_test.dart
+++ b/test/combined_wrapper/list_test.dart
@@ -11,7 +11,7 @@
var list1 = [1, 2, 3];
var list2 = [4, 5, 6];
var list3 = [7, 8, 9];
- var concat = <int>[]..addAll(list1)..addAll(list2)..addAll(list3);
+ var concat = <int>[...list1, ...list2, ...list3];
// In every way possible this should test the same as an UnmodifiableListView.
common.testUnmodifiableList(
@@ -52,7 +52,7 @@
listOfLists.add(list1);
expect(combined, list1);
listOfLists.add(list2);
- expect(combined, []..addAll(list1)..addAll(list2));
+ expect(combined, [...list1, ...list2]);
listOfLists.clear();
expect(combined, isEmpty);
});
diff --git a/test/comparators_test.dart b/test/comparators_test.dart
index 6a5cce8..b8dcb3e 100644
--- a/test/comparators_test.dart
+++ b/test/comparators_test.dart
@@ -2,79 +2,80 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
void main() {
- List<String> strings = [
- "",
- "\x00",
- " ",
- "+",
- "/",
- "0",
- "00",
- "000",
- "001",
- "01",
- "011",
- "1",
- "100",
- "11",
- "110",
- "9",
- ":",
- "=",
- "@",
- "A",
- "A0",
- "A000A",
- "A001A",
- "A00A",
- "A01A",
- "A0A",
- "A1A",
- "AA",
- "AAB",
- "AB",
- "Z",
- "[",
- "_",
- "`",
- "a",
- "a0",
- "a000a",
- "a001a",
- "a00a",
- "a01a",
- "a0a",
- "a1a",
- "aa",
- "aab",
- "ab",
- "z",
- "{",
- "~"
+ var strings = [
+ '',
+ '\x00',
+ ' ',
+ '+',
+ '/',
+ '0',
+ '00',
+ '000',
+ '001',
+ '01',
+ '011',
+ '1',
+ '100',
+ '11',
+ '110',
+ '9',
+ ':',
+ '=',
+ '@',
+ 'A',
+ 'A0',
+ 'A000A',
+ 'A001A',
+ 'A00A',
+ 'A01A',
+ 'A0A',
+ 'A1A',
+ 'AA',
+ 'AAB',
+ 'AB',
+ 'Z',
+ '[',
+ '_',
+ '`',
+ 'a',
+ 'a0',
+ 'a000a',
+ 'a001a',
+ 'a00a',
+ 'a01a',
+ 'a0a',
+ 'a1a',
+ 'aa',
+ 'aab',
+ 'ab',
+ 'z',
+ '{',
+ '~'
];
- List<String> sortedBy(int compare(String a, String b)) => strings.toList()
- ..shuffle()
- ..sort(compare);
+ List<String> sortedBy(int Function(String, String) compare) =>
+ strings.toList()
+ ..shuffle()
+ ..sort(compare);
- test("String.compareTo", () {
+ test('String.compareTo', () {
expect(sortedBy(null), strings);
});
- test("compareAsciiLowerCase", () {
+ test('compareAsciiLowerCase', () {
expect(sortedBy(compareAsciiLowerCase), sortedBy((a, b) {
- int delta = a.toLowerCase().compareTo(b.toLowerCase());
+ var delta = a.toLowerCase().compareTo(b.toLowerCase());
if (delta != 0) return delta;
if (a == b) return 0;
return a.compareTo(b);
}));
});
- test("compareAsciiUpperCase", () {
+ test('compareAsciiUpperCase', () {
expect(sortedBy(compareAsciiUpperCase), sortedBy((a, b) {
- int delta = a.toUpperCase().compareTo(b.toUpperCase());
+ var delta = a.toUpperCase().compareTo(b.toUpperCase());
if (delta != 0) return delta;
if (a == b) return 0;
return a.compareTo(b);
@@ -85,19 +86,20 @@
// This will sort alphabetically (by charcode) the way digits sort
// numerically, and the leading 0 means it sorts like a digit
// compared to non-digits.
- replaceNumbers(String string) => string.replaceAllMapped(RegExp(r"\d+"), (m) {
+ String replaceNumbers(String string) =>
+ string.replaceAllMapped(RegExp(r'\d+'), (m) {
var digits = m[0];
return String.fromCharCodes([0x30, int.parse(digits), digits.length]);
});
- test("compareNatural", () {
+ test('compareNatural', () {
expect(sortedBy(compareNatural),
sortedBy((a, b) => replaceNumbers(a).compareTo(replaceNumbers(b))));
});
- test("compareAsciiLowerCaseNatural", () {
+ test('compareAsciiLowerCaseNatural', () {
expect(sortedBy(compareAsciiLowerCaseNatural), sortedBy((a, b) {
- int delta = replaceNumbers(a.toLowerCase())
+ var delta = replaceNumbers(a.toLowerCase())
.compareTo(replaceNumbers(b.toLowerCase()));
if (delta != 0) return delta;
if (a == b) return 0;
@@ -105,9 +107,9 @@
}));
});
- test("compareAsciiUpperCaseNatural", () {
+ test('compareAsciiUpperCaseNatural', () {
expect(sortedBy(compareAsciiUpperCaseNatural), sortedBy((a, b) {
- int delta = replaceNumbers(a.toUpperCase())
+ var delta = replaceNumbers(a.toUpperCase())
.compareTo(replaceNumbers(b.toUpperCase()));
if (delta != 0) return delta;
if (a == b) return 0;
diff --git a/test/equality_map_test.dart b/test/equality_map_test.dart
index 64344fe..d3aa9fc 100644
--- a/test/equality_map_test.dart
+++ b/test/equality_map_test.dart
@@ -6,7 +6,7 @@
import 'package:test/test.dart';
void main() {
- test("uses the given equality", () {
+ test('uses the given equality', () {
var map = EqualityMap(const IterableEquality());
expect(map, isEmpty);
@@ -21,7 +21,7 @@
expect(map, containsPair([2, 3, 4], 3));
});
- test("EqualityMap.from() prefers the lattermost equivalent key", () {
+ test('EqualityMap.from() prefers the lattermost equivalent key', () {
var map = EqualityMap.from(const IterableEquality(), {
[1, 2, 3]: 1,
[2, 3, 4]: 2,
diff --git a/test/equality_set_test.dart b/test/equality_set_test.dart
index a99fe1f..1022726 100644
--- a/test/equality_set_test.dart
+++ b/test/equality_set_test.dart
@@ -6,7 +6,7 @@
import 'package:test/test.dart';
void main() {
- test("uses the given equality", () {
+ test('uses the given equality', () {
var set = EqualitySet(const IterableEquality());
expect(set, isEmpty);
@@ -27,7 +27,7 @@
expect(set, contains(same(list3)));
});
- test("EqualitySet.from() prefers the lattermost equivalent value", () {
+ test('EqualitySet.from() prefers the lattermost equivalent value', () {
var list1 = [1, 2, 3];
var list2 = [2, 3, 4];
var list3 = [1, 2, 3];
diff --git a/test/equality_test.dart b/test/equality_test.dart
index 2b3a229..b2109b6 100644
--- a/test/equality_test.dart
+++ b/test/equality_test.dart
@@ -4,12 +4,13 @@
// Tests equality utilities.
-import "dart:collection";
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'dart:collection';
-main() {
- o(Comparable id) => Element(id);
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
+
+void main() {
+ Element o(Comparable id) => Element(id);
// Lists that are point-wise equal, but not identical.
var list1 = [o(1), o(2), o(3), o(4), o(5)];
@@ -17,13 +18,13 @@
// Similar length list with equal elements in different order.
var list3 = [o(1), o(3), o(5), o(4), o(2)];
- test("IterableEquality - List", () {
+ test('IterableEquality - List', () {
expect(const IterableEquality().equals(list1, list2), isTrue);
Equality iterId = const IterableEquality(IdentityEquality());
expect(iterId.equals(list1, list2), isFalse);
});
- test("IterableEquality - LinkedSet", () {
+ test('IterableEquality - LinkedSet', () {
var l1 = LinkedHashSet.from(list1);
var l2 = LinkedHashSet.from(list2);
expect(const IterableEquality().equals(l1, l2), isTrue);
@@ -31,33 +32,33 @@
expect(iterId.equals(l1, l2), isFalse);
});
- test("ListEquality", () {
+ test('ListEquality', () {
expect(const ListEquality().equals(list1, list2), isTrue);
Equality listId = const ListEquality(IdentityEquality());
expect(listId.equals(list1, list2), isFalse);
});
- test("ListInequality length", () {
+ test('ListInequality length', () {
var list4 = [o(1), o(2), o(3), o(4), o(5), o(6)];
expect(const ListEquality().equals(list1, list4), isFalse);
expect(
const ListEquality(IdentityEquality()).equals(list1, list4), isFalse);
});
- test("ListInequality value", () {
+ test('ListInequality value', () {
var list5 = [o(1), o(2), o(3), o(4), o(6)];
expect(const ListEquality().equals(list1, list5), isFalse);
expect(
const ListEquality(IdentityEquality()).equals(list1, list5), isFalse);
});
- test("UnorderedIterableEquality", () {
+ test('UnorderedIterableEquality', () {
expect(const UnorderedIterableEquality().equals(list1, list3), isTrue);
Equality uniterId = const UnorderedIterableEquality(IdentityEquality());
expect(uniterId.equals(list1, list3), isFalse);
});
- test("UnorderedIterableInequality length", () {
+ test('UnorderedIterableInequality length', () {
var list6 = [o(1), o(3), o(5), o(4), o(2), o(1)];
expect(const UnorderedIterableEquality().equals(list1, list6), isFalse);
expect(
@@ -66,7 +67,7 @@
isFalse);
});
- test("UnorderedIterableInequality values", () {
+ test('UnorderedIterableInequality values', () {
var list7 = [o(1), o(3), o(5), o(4), o(6)];
expect(const UnorderedIterableEquality().equals(list1, list7), isFalse);
expect(
@@ -75,7 +76,7 @@
isFalse);
});
- test("SetEquality", () {
+ test('SetEquality', () {
var set1 = HashSet.from(list1);
var set2 = LinkedHashSet.from(list3);
expect(const SetEquality().equals(set1, set2), isTrue);
@@ -83,7 +84,7 @@
expect(setId.equals(set1, set2), isFalse);
});
- test("SetInequality length", () {
+ test('SetInequality length', () {
var list8 = [o(1), o(3), o(5), o(4), o(2), o(6)];
var set1 = HashSet.from(list1);
var set2 = LinkedHashSet.from(list8);
@@ -91,7 +92,7 @@
expect(const SetEquality(IdentityEquality()).equals(set1, set2), isFalse);
});
- test("SetInequality value", () {
+ test('SetInequality value', () {
var list7 = [o(1), o(3), o(5), o(4), o(6)];
var set1 = HashSet.from(list1);
var set2 = LinkedHashSet.from(list7);
@@ -100,32 +101,32 @@
});
var map1a = {
- "x": [o(1), o(2), o(3)],
- "y": [true, false, null]
+ 'x': [o(1), o(2), o(3)],
+ 'y': [true, false, null]
};
var map1b = {
- "x": [o(4), o(5), o(6)],
- "y": [false, true, null]
+ 'x': [o(4), o(5), o(6)],
+ 'y': [false, true, null]
};
var map2a = {
- "x": [o(3), o(2), o(1)],
- "y": [false, true, null]
+ 'x': [o(3), o(2), o(1)],
+ 'y': [false, true, null]
};
var map2b = {
- "x": [o(6), o(5), o(4)],
- "y": [null, false, true]
+ 'x': [o(6), o(5), o(4)],
+ 'y': [null, false, true]
};
var l1 = [map1a, map1b];
var l2 = [map2a, map2b];
- var s1 = Set<Map>.from(l1);
- var s2 = Set<Map>.from([map2b, map2a]);
+ var s1 = {...l1};
+ var s2 = {map2b, map2a};
- test("RecursiveEquality", () {
+ test('RecursiveEquality', () {
const unordered = UnorderedIterableEquality();
- expect(unordered.equals(map1a["x"], map2a["x"]), isTrue);
- expect(unordered.equals(map1a["y"], map2a["y"]), isTrue);
- expect(unordered.equals(map1b["x"], map2b["x"]), isTrue);
- expect(unordered.equals(map1b["y"], map2b["y"]), isTrue);
+ expect(unordered.equals(map1a['x'], map2a['x']), isTrue);
+ expect(unordered.equals(map1a['y'], map2a['y']), isTrue);
+ expect(unordered.equals(map1b['x'], map2b['x']), isTrue);
+ expect(unordered.equals(map1b['y'], map2b['y']), isTrue);
const mapval = MapEquality(values: unordered);
expect(mapval.equals(map1a, map2a), isTrue);
expect(mapval.equals(map1b, map2b), isTrue);
@@ -135,62 +136,62 @@
expect(setmapval.equals(s1, s2), isTrue);
});
- test("DeepEquality", () {
+ test('DeepEquality', () {
var colleq = const DeepCollectionEquality.unordered();
- expect(colleq.equals(map1a["x"], map2a["x"]), isTrue);
- expect(colleq.equals(map1a["y"], map2a["y"]), isTrue);
- expect(colleq.equals(map1b["x"], map2b["x"]), isTrue);
- expect(colleq.equals(map1b["y"], map2b["y"]), isTrue);
+ expect(colleq.equals(map1a['x'], map2a['x']), isTrue);
+ expect(colleq.equals(map1a['y'], map2a['y']), isTrue);
+ expect(colleq.equals(map1b['x'], map2b['x']), isTrue);
+ expect(colleq.equals(map1b['y'], map2b['y']), isTrue);
expect(colleq.equals(map1a, map2a), isTrue);
expect(colleq.equals(map1b, map2b), isTrue);
expect(colleq.equals(l1, l2), isTrue);
expect(colleq.equals(s1, s2), isTrue);
});
- test("CaseInsensitiveEquality", () {
+ test('CaseInsensitiveEquality', () {
var equality = const CaseInsensitiveEquality();
- expect(equality.equals("foo", "foo"), isTrue);
- expect(equality.equals("fOo", "FoO"), isTrue);
- expect(equality.equals("FoO", "fOo"), isTrue);
- expect(equality.equals("foo", "bar"), isFalse);
- expect(equality.equals("fÕÕ", "fõõ"), isFalse);
+ expect(equality.equals('foo', 'foo'), isTrue);
+ expect(equality.equals('fOo', 'FoO'), isTrue);
+ expect(equality.equals('FoO', 'fOo'), isTrue);
+ expect(equality.equals('foo', 'bar'), isFalse);
+ expect(equality.equals('fÕÕ', 'fõõ'), isFalse);
- expect(equality.hash("foo"), equals(equality.hash("foo")));
- expect(equality.hash("fOo"), equals(equality.hash("FoO")));
- expect(equality.hash("FoO"), equals(equality.hash("fOo")));
- expect(equality.hash("foo"), isNot(equals(equality.hash("bar"))));
- expect(equality.hash("fÕÕ"), isNot(equals(equality.hash("fõõ"))));
+ expect(equality.hash('foo'), equals(equality.hash('foo')));
+ expect(equality.hash('fOo'), equals(equality.hash('FoO')));
+ expect(equality.hash('FoO'), equals(equality.hash('fOo')));
+ expect(equality.hash('foo'), isNot(equals(equality.hash('bar'))));
+ expect(equality.hash('fÕÕ'), isNot(equals(equality.hash('fõõ'))));
});
- group("EqualityBy should use a derived value for ", () {
+ group('EqualityBy should use a derived value for ', () {
var firstEquality = EqualityBy<List<String>, String>((e) => e.first);
var firstInsensitiveEquality = EqualityBy<List<String>, String>(
(e) => e.first, const CaseInsensitiveEquality());
var firstObjectEquality = EqualityBy<List<Object>, Object>(
(e) => e.first, const IterableEquality());
- test("equality", () {
- expect(firstEquality.equals(["foo", "foo"], ["foo", "bar"]), isTrue);
- expect(firstEquality.equals(["foo", "foo"], ["bar", "bar"]), isFalse);
+ test('equality', () {
+ expect(firstEquality.equals(['foo', 'foo'], ['foo', 'bar']), isTrue);
+ expect(firstEquality.equals(['foo', 'foo'], ['bar', 'bar']), isFalse);
});
- test("equality with an inner equality", () {
- expect(firstInsensitiveEquality.equals(["fOo"], ["FoO"]), isTrue);
- expect(firstInsensitiveEquality.equals(["foo"], ["ffõõ"]), isFalse);
+ test('equality with an inner equality', () {
+ expect(firstInsensitiveEquality.equals(['fOo'], ['FoO']), isTrue);
+ expect(firstInsensitiveEquality.equals(['foo'], ['ffõõ']), isFalse);
});
- test("hash", () {
- expect(firstEquality.hash(["foo", "bar"]), "foo".hashCode);
+ test('hash', () {
+ expect(firstEquality.hash(['foo', 'bar']), 'foo'.hashCode);
});
- test("hash with an inner equality", () {
- expect(firstInsensitiveEquality.hash(["fOo"]),
- const CaseInsensitiveEquality().hash("foo"));
+ test('hash with an inner equality', () {
+ expect(firstInsensitiveEquality.hash(['fOo']),
+ const CaseInsensitiveEquality().hash('foo'));
});
- test("isValidKey", () {
- expect(firstEquality.isValidKey(["foo"]), isTrue);
- expect(firstEquality.isValidKey("foo"), isFalse);
+ test('isValidKey', () {
+ expect(firstEquality.isValidKey(['foo']), isTrue);
+ expect(firstEquality.isValidKey('foo'), isFalse);
expect(firstEquality.isValidKey([1]), isFalse);
});
@@ -200,7 +201,7 @@
});
});
- test("Equality accepts null", () {
+ test('Equality accepts null', () {
var ie = IterableEquality();
var le = ListEquality();
var se = SetEquality();
@@ -216,8 +217,8 @@
expect(le.hash(null), null.hashCode);
expect(se.equals(null, null), true);
- expect(se.equals(Set(), null), false);
- expect(se.equals(null, Set()), false);
+ expect(se.equals({}, null), false);
+ expect(se.equals(null, {}), false);
expect(se.hash(null), null.hashCode);
expect(me.equals(null, null), true);
@@ -234,7 +235,10 @@
class Element implements Comparable<Element> {
final Comparable id;
const Element(this.id);
+ @override
int get hashCode => id.hashCode;
+ @override
bool operator ==(Object other) => other is Element && id == other.id;
+ @override
int compareTo(other) => id.compareTo(other.id);
}
diff --git a/test/functions_test.dart b/test/functions_test.dart
index e754d54..f18ec2f 100644
--- a/test/functions_test.dart
+++ b/test/functions_test.dart
@@ -2,13 +2,13 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:test/test.dart";
+import 'package:test/test.dart';
-import "package:collection/collection.dart";
+import 'package:collection/collection.dart';
void main() {
- group("mapMap()", () {
- test("with an empty map returns an empty map", () {
+ group('mapMap()', () {
+ test('with an empty map returns an empty map', () {
expect(
mapMap({},
key: expectAsync2((_, __) {}, count: 0),
@@ -16,77 +16,77 @@
isEmpty);
});
- test("with no callbacks, returns a copy of the map", () {
- var map = {"foo": 1, "bar": 2};
+ test('with no callbacks, returns a copy of the map', () {
+ var map = {'foo': 1, 'bar': 2};
var result = mapMap(map);
- expect(result, equals({"foo": 1, "bar": 2}));
+ expect(result, equals({'foo': 1, 'bar': 2}));
// The resulting map should be a copy.
- result["foo"] = 3;
- expect(map, equals({"foo": 1, "bar": 2}));
+ result['foo'] = 3;
+ expect(map, equals({'foo': 1, 'bar': 2}));
});
test("maps the map's keys", () {
- expect(mapMap({"foo": 1, "bar": 2}, key: (key, value) => key[value]),
- equals({"o": 1, "r": 2}));
+ expect(mapMap({'foo': 1, 'bar': 2}, key: (key, value) => key[value]),
+ equals({'o': 1, 'r': 2}));
});
test("maps the map's values", () {
- expect(mapMap({"foo": 1, "bar": 2}, value: (key, value) => key[value]),
- equals({"foo": "o", "bar": "r"}));
+ expect(mapMap({'foo': 1, 'bar': 2}, value: (key, value) => key[value]),
+ equals({'foo': 'o', 'bar': 'r'}));
});
test("maps both the map's keys and values", () {
expect(
- mapMap({"foo": 1, "bar": 2},
- key: (key, value) => "$key$value",
+ mapMap({'foo': 1, 'bar': 2},
+ key: (key, value) => '$key$value',
value: (key, value) => key[value]),
- equals({"foo1": "o", "bar2": "r"}));
+ equals({'foo1': 'o', 'bar2': 'r'}));
});
});
- group("mergeMaps()", () {
- test("with empty maps returns an empty map", () {
+ group('mergeMaps()', () {
+ test('with empty maps returns an empty map', () {
expect(mergeMaps({}, {}, value: expectAsync2((_, __) {}, count: 0)),
isEmpty);
});
- test("returns a map with all values in both input maps", () {
- expect(mergeMaps({"foo": 1, "bar": 2}, {"baz": 3, "qux": 4}),
- equals({"foo": 1, "bar": 2, "baz": 3, "qux": 4}));
+ test('returns a map with all values in both input maps', () {
+ expect(mergeMaps({'foo': 1, 'bar': 2}, {'baz': 3, 'qux': 4}),
+ equals({'foo': 1, 'bar': 2, 'baz': 3, 'qux': 4}));
});
test("the second map's values win by default", () {
- expect(mergeMaps({"foo": 1, "bar": 2}, {"bar": 3, "baz": 4}),
- equals({"foo": 1, "bar": 3, "baz": 4}));
+ expect(mergeMaps({'foo': 1, 'bar': 2}, {'bar': 3, 'baz': 4}),
+ equals({'foo': 1, 'bar': 3, 'baz': 4}));
});
- test("uses the callback to merge values", () {
+ test('uses the callback to merge values', () {
expect(
- mergeMaps({"foo": 1, "bar": 2}, {"bar": 3, "baz": 4},
+ mergeMaps({'foo': 1, 'bar': 2}, {'bar': 3, 'baz': 4},
value: (value1, value2) => value1 + value2),
- equals({"foo": 1, "bar": 5, "baz": 4}));
+ equals({'foo': 1, 'bar': 5, 'baz': 4}));
});
});
- group("groupBy()", () {
- test("returns an empty map for an empty iterable", () {
+ group('groupBy()', () {
+ test('returns an empty map for an empty iterable', () {
expect(groupBy([], expectAsync1((_) {}, count: 0)), isEmpty);
});
test("groups elements by the function's return value", () {
expect(
- groupBy(["foo", "bar", "baz", "bop", "qux"], (string) => string[1]),
+ groupBy(['foo', 'bar', 'baz', 'bop', 'qux'], (string) => string[1]),
equals({
- "o": ["foo", "bop"],
- "a": ["bar", "baz"],
- "u": ["qux"]
+ 'o': ['foo', 'bop'],
+ 'a': ['bar', 'baz'],
+ 'u': ['qux']
}));
});
});
- group("minBy()", () {
- test("returns null for an empty iterable", () {
+ group('minBy()', () {
+ test('returns null for an empty iterable', () {
expect(
minBy([], expectAsync1((_) {}, count: 0),
compare: expectAsync2((_, __) => null, count: 0)),
@@ -94,35 +94,35 @@
});
test(
- "returns the element for which the ordering function returns the "
- "smallest value", () {
+ 'returns the element for which the ordering function returns the '
+ 'smallest value', () {
expect(
minBy([
- {"foo": 3},
- {"foo": 5},
- {"foo": 4},
- {"foo": 1},
- {"foo": 2}
- ], (map) => map["foo"]),
- equals({"foo": 1}));
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2}
+ ], (map) => map['foo']),
+ equals({'foo': 1}));
});
- test("uses a custom comparator if provided", () {
+ test('uses a custom comparator if provided', () {
expect(
minBy<Map<String, int>, Map<String, int>>([
- {"foo": 3},
- {"foo": 5},
- {"foo": 4},
- {"foo": 1},
- {"foo": 2}
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2}
], (map) => map,
- compare: (map1, map2) => map1["foo"].compareTo(map2["foo"])),
- equals({"foo": 1}));
+ compare: (map1, map2) => map1['foo'].compareTo(map2['foo'])),
+ equals({'foo': 1}));
});
});
- group("maxBy()", () {
- test("returns null for an empty iterable", () {
+ group('maxBy()', () {
+ test('returns null for an empty iterable', () {
expect(
maxBy([], expectAsync1((_) {}, count: 0),
compare: expectAsync2((_, __) => null, count: 0)),
@@ -130,202 +130,202 @@
});
test(
- "returns the element for which the ordering function returns the "
- "largest value", () {
+ 'returns the element for which the ordering function returns the '
+ 'largest value', () {
expect(
maxBy([
- {"foo": 3},
- {"foo": 5},
- {"foo": 4},
- {"foo": 1},
- {"foo": 2}
- ], (map) => map["foo"]),
- equals({"foo": 5}));
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2}
+ ], (map) => map['foo']),
+ equals({'foo': 5}));
});
- test("uses a custom comparator if provided", () {
+ test('uses a custom comparator if provided', () {
expect(
maxBy<Map<String, int>, Map<String, int>>([
- {"foo": 3},
- {"foo": 5},
- {"foo": 4},
- {"foo": 1},
- {"foo": 2}
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2}
], (map) => map,
- compare: (map1, map2) => map1["foo"].compareTo(map2["foo"])),
- equals({"foo": 5}));
+ compare: (map1, map2) => map1['foo'].compareTo(map2['foo'])),
+ equals({'foo': 5}));
});
});
- group("transitiveClosure()", () {
- test("returns an empty map for an empty graph", () {
+ group('transitiveClosure()', () {
+ test('returns an empty map for an empty graph', () {
expect(transitiveClosure({}), isEmpty);
});
- test("returns the input when there are no transitive connections", () {
+ test('returns the input when there are no transitive connections', () {
expect(
transitiveClosure({
- "foo": ["bar"],
- "bar": [],
- "bang": ["qux", "zap"],
- "qux": [],
- "zap": []
+ 'foo': ['bar'],
+ 'bar': [],
+ 'bang': ['qux', 'zap'],
+ 'qux': [],
+ 'zap': []
}),
equals({
- "foo": ["bar"],
- "bar": [],
- "bang": ["qux", "zap"],
- "qux": [],
- "zap": []
+ 'foo': ['bar'],
+ 'bar': [],
+ 'bang': ['qux', 'zap'],
+ 'qux': [],
+ 'zap': []
}));
});
- test("flattens transitive connections", () {
+ test('flattens transitive connections', () {
expect(
transitiveClosure({
- "qux": [],
- "bar": ["baz"],
- "baz": ["qux"],
- "foo": ["bar"]
+ 'qux': [],
+ 'bar': ['baz'],
+ 'baz': ['qux'],
+ 'foo': ['bar']
}),
equals({
- "foo": ["bar", "baz", "qux"],
- "bar": ["baz", "qux"],
- "baz": ["qux"],
- "qux": []
+ 'foo': ['bar', 'baz', 'qux'],
+ 'bar': ['baz', 'qux'],
+ 'baz': ['qux'],
+ 'qux': []
}));
});
- test("handles loops", () {
+ test('handles loops', () {
expect(
transitiveClosure({
- "foo": ["bar"],
- "bar": ["baz"],
- "baz": ["foo"]
+ 'foo': ['bar'],
+ 'bar': ['baz'],
+ 'baz': ['foo']
}),
equals({
- "foo": ["bar", "baz", "foo"],
- "bar": ["baz", "foo", "bar"],
- "baz": ["foo", "bar", "baz"]
+ 'foo': ['bar', 'baz', 'foo'],
+ 'bar': ['baz', 'foo', 'bar'],
+ 'baz': ['foo', 'bar', 'baz']
}));
});
});
- group("stronglyConnectedComponents()", () {
- test("returns an empty list for an empty graph", () {
+ group('stronglyConnectedComponents()', () {
+ test('returns an empty list for an empty graph', () {
expect(stronglyConnectedComponents({}), isEmpty);
});
- test("returns one set for a singleton graph", () {
+ test('returns one set for a singleton graph', () {
expect(
- stronglyConnectedComponents({"a": []}),
+ stronglyConnectedComponents({'a': []}),
equals([
- Set.from(["a"])
+ {'a'}
]));
});
- test("returns two sets for a two-element tree", () {
+ test('returns two sets for a two-element tree', () {
expect(
stronglyConnectedComponents({
- "a": ["b"],
- "b": []
+ 'a': ['b'],
+ 'b': []
}),
equals([
- Set.from(["a"]),
- Set.from(["b"])
+ {'a'},
+ {'b'}
]));
});
- test("returns one set for a two-element loop", () {
+ test('returns one set for a two-element loop', () {
expect(
stronglyConnectedComponents({
- "a": ["b"],
- "b": ["a"]
+ 'a': ['b'],
+ 'b': ['a']
}),
equals([
- Set.from(["a", "b"])
+ {'a', 'b'}
]));
});
- test("returns individual vertices for a tree", () {
+ test('returns individual vertices for a tree', () {
expect(
stronglyConnectedComponents({
- "foo": ["bar"],
- "bar": ["baz", "bang"],
- "baz": ["qux"],
- "bang": ["zap"],
- "qux": [],
- "zap": []
+ 'foo': ['bar'],
+ 'bar': ['baz', 'bang'],
+ 'baz': ['qux'],
+ 'bang': ['zap'],
+ 'qux': [],
+ 'zap': []
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
// the only valid one. If the function implementation changes in the
// future, this test may need to be updated.
- Set.from(["foo"]),
- Set.from(["bar"]),
- Set.from(["bang"]),
- Set.from(["zap"]),
- Set.from(["baz"]),
- Set.from(["qux"])
+ {'foo'},
+ {'bar'},
+ {'bang'},
+ {'zap'},
+ {'baz'},
+ {'qux'}
]));
});
- test("returns a single set for a fully cyclic graph", () {
+ test('returns a single set for a fully cyclic graph', () {
expect(
stronglyConnectedComponents({
- "foo": ["bar"],
- "bar": ["baz"],
- "baz": ["bang"],
- "bang": ["foo"]
+ 'foo': ['bar'],
+ 'bar': ['baz'],
+ 'baz': ['bang'],
+ 'bang': ['foo']
}),
equals([
- Set.from(["foo", "bar", "baz", "bang"])
+ {'foo', 'bar', 'baz', 'bang'}
]));
});
- test("returns separate sets for each strongly connected component", () {
+ test('returns separate sets for each strongly connected component', () {
// https://en.wikipedia.org/wiki/Strongly_connected_component#/media/File:Scc.png
expect(
stronglyConnectedComponents({
- "a": ["b"],
- "b": ["c", "e", "f"],
- "c": ["d", "g"],
- "d": ["c", "h"],
- "e": ["a", "f"],
- "f": ["g"],
- "g": ["f"],
- "h": ["g", "d"]
+ 'a': ['b'],
+ 'b': ['c', 'e', 'f'],
+ 'c': ['d', 'g'],
+ 'd': ['c', 'h'],
+ 'e': ['a', 'f'],
+ 'f': ['g'],
+ 'g': ['f'],
+ 'h': ['g', 'd']
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
// the only valid one. If the function implementation changes in the
// future, this test may need to be updated.
- Set.from(["a", "b", "e"]),
- Set.from(["c", "d", "h"]),
- Set.from(["f", "g"]),
+ {'a', 'b', 'e'},
+ {'c', 'd', 'h'},
+ {'f', 'g'},
]));
});
- test("always returns components in topological order", () {
+ test('always returns components in topological order', () {
expect(
stronglyConnectedComponents({
- "bar": ["baz", "bang"],
- "zap": [],
- "baz": ["qux"],
- "qux": [],
- "foo": ["bar"],
- "bang": ["zap"]
+ 'bar': ['baz', 'bang'],
+ 'zap': [],
+ 'baz': ['qux'],
+ 'qux': [],
+ 'foo': ['bar'],
+ 'bang': ['zap']
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
// the only valid one. If the function implementation changes in the
// future, this test may need to be updated.
- Set.from(["foo"]),
- Set.from(["bar"]),
- Set.from(["bang"]),
- Set.from(["zap"]),
- Set.from(["baz"]),
- Set.from(["qux"])
+ {'foo'},
+ {'bar'},
+ {'bang'},
+ {'zap'},
+ {'baz'},
+ {'qux'}
]));
});
});
diff --git a/test/ignore_ascii_case_test.dart b/test/ignore_ascii_case_test.dart
index 5e3ee4f..20ad70f 100644
--- a/test/ignore_ascii_case_test.dart
+++ b/test/ignore_ascii_case_test.dart
@@ -4,51 +4,51 @@
/// Tests case-ignoring compare and equality.
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
-main() {
- test("equality ignore ASCII case", () {
+void main() {
+ test('equality ignore ASCII case', () {
var strings = [
- "0@`aopz[{",
- "0@`aopz[{",
- "0@`Aopz[{",
- "0@`aOpz[{",
- "0@`AOpz[{",
- "0@`aoPz[{",
- "0@`AoPz[{",
- "0@`aOPz[{",
- "0@`AOPz[{",
- "0@`aopZ[{",
- "0@`AopZ[{",
- "0@`aOpZ[{",
- "0@`AOpZ[{",
- "0@`aoPZ[{",
- "0@`AoPZ[{",
- "0@`aOPZ[{",
- "0@`AOPZ[{",
+ '0@`aopz[{',
+ '0@`aopz[{',
+ '0@`Aopz[{',
+ '0@`aOpz[{',
+ '0@`AOpz[{',
+ '0@`aoPz[{',
+ '0@`AoPz[{',
+ '0@`aOPz[{',
+ '0@`AOPz[{',
+ '0@`aopZ[{',
+ '0@`AopZ[{',
+ '0@`aOpZ[{',
+ '0@`AOpZ[{',
+ '0@`aoPZ[{',
+ '0@`AoPZ[{',
+ '0@`aOPZ[{',
+ '0@`AOPZ[{',
];
for (var s1 in strings) {
for (var s2 in strings) {
- var reason = "$s1 =?= $s2";
+ var reason = '$s1 =?= $s2';
expect(equalsIgnoreAsciiCase(s1, s2), true, reason: reason);
expect(hashIgnoreAsciiCase(s1), hashIgnoreAsciiCase(s2),
reason: reason);
}
}
- var upperCaseLetters = "@`abcdefghijklmnopqrstuvwxyz[{åÅ";
- var lowerCaseLetters = "@`ABCDEFGHIJKLMNOPQRSTUVWXYZ[{åÅ";
+ var upperCaseLetters = '@`abcdefghijklmnopqrstuvwxyz[{åÅ';
+ var lowerCaseLetters = '@`ABCDEFGHIJKLMNOPQRSTUVWXYZ[{åÅ';
expect(equalsIgnoreAsciiCase(upperCaseLetters, lowerCaseLetters), true);
- testChars(String char1, String char2, bool areEqual) {
+ void testChars(String char1, String char2, bool areEqual) {
expect(equalsIgnoreAsciiCase(char1, char2), areEqual,
reason: "$char1 ${areEqual ? "=" : "!"}= $char2");
}
- for (int i = 0; i < upperCaseLetters.length; i++) {
- for (int j = 0; i < upperCaseLetters.length; i++) {
+ for (var i = 0; i < upperCaseLetters.length; i++) {
+ for (var j = 0; i < upperCaseLetters.length; i++) {
testChars(upperCaseLetters[i], upperCaseLetters[j], i == j);
testChars(lowerCaseLetters[i], upperCaseLetters[j], i == j);
testChars(upperCaseLetters[i], lowerCaseLetters[j], i == j);
diff --git a/test/iterable_zip_test.dart b/test/iterable_zip_test.dart
index 75a448d..991feda 100644
--- a/test/iterable_zip_test.dart
+++ b/test/iterable_zip_test.dart
@@ -2,20 +2,18 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "dart:collection";
+import 'package:test/test.dart';
-import "package:test/test.dart";
-
-import "package:collection/collection.dart";
+import 'package:collection/collection.dart';
/// Iterable like [base] except that it throws when value equals [errorValue].
Iterable iterError(Iterable base, int errorValue) {
// ignore: only_throw_errors
- return base.map((x) => x == errorValue ? throw "BAD" : x);
+ return base.map((x) => x == errorValue ? throw 'BAD' : x);
}
-main() {
- test("Basic", () {
+void main() {
+ test('Basic', () {
expect(
IterableZip([
[1, 2, 3],
@@ -29,7 +27,7 @@
]));
});
- test("Uneven length 1", () {
+ test('Uneven length 1', () {
expect(
IterableZip([
[1, 2, 3, 99, 100],
@@ -43,7 +41,7 @@
]));
});
- test("Uneven length 2", () {
+ test('Uneven length 2', () {
expect(
IterableZip([
[1, 2, 3],
@@ -57,7 +55,7 @@
]));
});
- test("Uneven length 3", () {
+ test('Uneven length 3', () {
expect(
IterableZip([
[1, 2, 3],
@@ -71,7 +69,7 @@
]));
});
- test("Uneven length 3", () {
+ test('Uneven length 3', () {
expect(
IterableZip([
[1, 2, 3, 98],
@@ -85,7 +83,7 @@
]));
});
- test("Empty 1", () {
+ test('Empty 1', () {
expect(
IterableZip([
[],
@@ -95,7 +93,7 @@
equals([]));
});
- test("Empty 2", () {
+ test('Empty 2', () {
expect(
IterableZip([
[1, 2, 3],
@@ -105,7 +103,7 @@
equals([]));
});
- test("Empty 3", () {
+ test('Empty 3', () {
expect(
IterableZip([
[1, 2, 3],
@@ -115,11 +113,11 @@
equals([]));
});
- test("Empty source", () {
+ test('Empty source', () {
expect(IterableZip([]), equals([]));
});
- test("Single Source", () {
+ test('Single Source', () {
expect(
IterableZip([
[1, 2, 3]
@@ -131,16 +129,12 @@
]));
});
- test("Not-lists", () {
+ test('Not-lists', () {
// Use other iterables than list literals.
- Iterable it1 = [1, 2, 3, 4, 5, 6].where((x) => x < 4);
- Set it2 = LinkedHashSet()..add(4)..add(5)..add(6);
- Iterable it3 = (LinkedHashMap()
- ..[7] = 0
- ..[8] = 0
- ..[9] = 0)
- .keys;
- Iterable<Iterable> allIts = Iterable.generate(3, (i) => [it1, it2, it3][i]);
+ var it1 = [1, 2, 3, 4, 5, 6].where((x) => x < 4);
+ var it2 = {4, 5, 6};
+ var it3 = {7: 0, 8: 0, 9: 0}.keys;
+ var allIts = Iterable.generate(3, (i) => [it1, it2, it3][i]);
expect(
IterableZip(allIts),
equals([
@@ -150,57 +144,57 @@
]));
});
- test("Error 1", () {
+ test('Error 1', () {
expect(
() => IterableZip([
iterError([1, 2, 3], 2),
[4, 5, 6],
[7, 8, 9]
]).toList(),
- throwsA(equals("BAD")));
+ throwsA(equals('BAD')));
});
- test("Error 2", () {
+ test('Error 2', () {
expect(
() => IterableZip([
[1, 2, 3],
iterError([4, 5, 6], 5),
[7, 8, 9]
]).toList(),
- throwsA(equals("BAD")));
+ throwsA(equals('BAD')));
});
- test("Error 3", () {
+ test('Error 3', () {
expect(
() => IterableZip([
[1, 2, 3],
[4, 5, 6],
iterError([7, 8, 9], 8)
]).toList(),
- throwsA(equals("BAD")));
+ throwsA(equals('BAD')));
});
- test("Error at end", () {
+ test('Error at end', () {
expect(
() => IterableZip([
[1, 2, 3],
iterError([4, 5, 6], 6),
[7, 8, 9]
]).toList(),
- throwsA(equals("BAD")));
+ throwsA(equals('BAD')));
});
- test("Error before first end", () {
+ test('Error before first end', () {
expect(
() => IterableZip([
iterError([1, 2, 3, 4], 4),
[4, 5, 6],
[7, 8, 9]
]).toList(),
- throwsA(equals("BAD")));
+ throwsA(equals('BAD')));
});
- test("Error after first end", () {
+ test('Error after first end', () {
expect(
IterableZip([
[1, 2, 3],
diff --git a/test/priority_queue_test.dart b/test/priority_queue_test.dart
index aefd346..03e2253 100644
--- a/test/priority_queue_test.dart
+++ b/test/priority_queue_test.dart
@@ -4,9 +4,9 @@
/// Tests priority queue implementations utilities.
-import "package:test/test.dart";
+import 'package:test/test.dart';
-import "package:collection/src/priority_queue.dart";
+import 'package:collection/src/priority_queue.dart';
void main() {
testDefault();
@@ -22,19 +22,20 @@
testCustom((comparator) => PriorityQueue<C>(comparator));
}
-void testInt(PriorityQueue<int> create()) {
- for (int count in [1, 5, 127, 128]) {
- testQueue("int:$count", create, List<int>.generate(count, (x) => x), count);
+void testInt(PriorityQueue<int> Function() create) {
+ for (var count in [1, 5, 127, 128]) {
+ testQueue('int:$count', create, List<int>.generate(count, (x) => x), count);
}
}
-void testCustom(PriorityQueue<C> create(int comparator(C a, C b))) {
- for (int count in [1, 5, 127, 128]) {
- testQueue("Custom:$count/null", () => create(null),
+void testCustom(
+ PriorityQueue<C> Function(int Function(C, C) comparator) create) {
+ for (var count in [1, 5, 127, 128]) {
+ testQueue('Custom:$count/null', () => create(null),
List<C>.generate(count, (x) => C(x)), C(count));
- testQueue("Custom:$count/compare", () => create(compare),
+ testQueue('Custom:$count/compare', () => create(compare),
List<C>.generate(count, (x) => C(x)), C(count));
- testQueue("Custom:$count/compareNeg", () => create(compareNeg),
+ testQueue('Custom:$count/compareNeg', () => create(compareNeg),
List<C>.generate(count, (x) => C(count - x)), C(0));
}
}
@@ -42,12 +43,13 @@
/// Test that a queue behaves correctly.
///
/// The elements must be in priority order, from highest to lowest.
-void testQueue(String name, PriorityQueue create(), List elements, notElement) {
+void testQueue(
+ String name, PriorityQueue Function() create, List elements, notElement) {
test(name, () => testQueueBody(create, elements, notElement));
}
-void testQueueBody(PriorityQueue create(), List elements, notElement) {
- PriorityQueue q = create();
+void testQueueBody(PriorityQueue Function() create, List elements, notElement) {
+ var q = create();
expect(q.isEmpty, isTrue);
expect(q, hasLength(0));
expect(() {
@@ -65,12 +67,12 @@
expect(q.toList(), equals(elements));
expect(q.toSet().toList(), equals(elements));
- for (int i = 0; i < elements.length; i++) {
+ for (var i = 0; i < elements.length; i++) {
expect(q.contains(elements[i]), isTrue);
}
expect(q.contains(notElement), isFalse);
- List all = [];
+ var all = [];
while (q.isNotEmpty) {
var expected = q.first;
var actual = q.removeFirst();
@@ -79,7 +81,7 @@
}
expect(all.length, elements.length);
- for (int i = 0; i < all.length; i++) {
+ for (var i = 0; i < all.length; i++) {
expect(all[i], same(elements[i]));
}
@@ -93,7 +95,7 @@
testElements();
// Add elements in a non-linear order (gray order).
- for (int i = 0, j = 0; i < elements.length; i++) {
+ for (var i = 0, j = 0; i < elements.length; i++) {
int gray;
do {
gray = j ^ (j >> 1);
@@ -106,7 +108,7 @@
// Add elements by picking the middle element first, and then recursing
// on each side.
void addRec(int min, int max) {
- int mid = min + ((max - min) >> 1);
+ var mid = min + ((max - min) >> 1);
q.add(elements[mid]);
if (mid + 1 < max) addRec(mid + 1, max);
if (mid > min) addRec(min, mid);
@@ -118,10 +120,10 @@
// Test removeAll.
q.addAll(elements);
expect(q, hasLength(elements.length));
- Iterable all = q.removeAll();
+ var all = q.removeAll();
expect(q.isEmpty, isTrue);
expect(all, hasLength(elements.length));
- for (int i = 0; i < elements.length; i++) {
+ for (var i = 0; i < elements.length; i++) {
expect(all, contains(elements[i]));
}
@@ -129,7 +131,7 @@
q.addAll(elements);
q.addAll(elements.reversed);
expect(q, hasLength(elements.length * 2));
- for (int i = 0; i < elements.length; i++) {
+ for (var i = 0; i < elements.length; i++) {
var element = elements[i];
expect(q.contains(element), isTrue);
expect(q.removeFirst(), element);
@@ -138,7 +140,7 @@
// Test queue with all same element.
var a = elements[0];
- for (int i = 0; i < elements.length; i++) {
+ for (var i = 0; i < elements.length; i++) {
q.add(a);
}
expect(q, hasLength(elements.length));
@@ -162,8 +164,12 @@
class C implements Comparable<C> {
final int value;
const C(this.value);
+ @override
int get hashCode => value;
+ @override
bool operator ==(Object other) => other is C && value == other.value;
+ @override
int compareTo(C other) => value - other.value;
- String toString() => "C($value)";
+ @override
+ String toString() => 'C($value)';
}
diff --git a/test/queue_list_test.dart b/test/queue_list_test.dart
index 9522a39..4099308 100644
--- a/test/queue_list_test.dart
+++ b/test/queue_list_test.dart
@@ -2,159 +2,159 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
-import "utils.dart";
+import 'utils.dart';
void main() {
- group("new QueueList()", () {
- test("creates an empty QueueList", () {
+ group('new QueueList()', () {
+ test('creates an empty QueueList', () {
expect(QueueList(), isEmpty);
});
- test("takes an initial capacity", () {
+ test('takes an initial capacity', () {
expect(QueueList(100), isEmpty);
});
});
- test("new QueueList.from() copies the contents of an iterable", () {
+ test('new QueueList.from() copies the contents of an iterable', () {
expect(QueueList.from([1, 2, 3].skip(1)), equals([2, 3]));
});
- group("add()", () {
- test("adds an element to the end of the queue", () {
+ group('add()', () {
+ test('adds an element to the end of the queue', () {
var queue = QueueList.from([1, 2, 3]);
queue.add(4);
expect(queue, equals([1, 2, 3, 4]));
});
- test("expands a full queue", () {
+ test('expands a full queue', () {
var queue = atCapacity();
queue.add(8);
expect(queue, equals([1, 2, 3, 4, 5, 6, 7, 8]));
});
});
- group("addAll()", () {
- test("adds elements to the end of the queue", () {
+ group('addAll()', () {
+ test('adds elements to the end of the queue', () {
var queue = QueueList.from([1, 2, 3]);
queue.addAll([4, 5, 6]);
expect(queue, equals([1, 2, 3, 4, 5, 6]));
});
- test("expands a full queue", () {
+ test('expands a full queue', () {
var queue = atCapacity();
queue.addAll([8, 9]);
expect(queue, equals([1, 2, 3, 4, 5, 6, 7, 8, 9]));
});
});
- group("addFirst()", () {
- test("adds an element to the beginning of the queue", () {
+ group('addFirst()', () {
+ test('adds an element to the beginning of the queue', () {
var queue = QueueList.from([1, 2, 3]);
queue.addFirst(0);
expect(queue, equals([0, 1, 2, 3]));
});
- test("expands a full queue", () {
+ test('expands a full queue', () {
var queue = atCapacity();
queue.addFirst(0);
expect(queue, equals([0, 1, 2, 3, 4, 5, 6, 7]));
});
});
- group("removeFirst()", () {
- test("removes an element from the beginning of the queue", () {
+ group('removeFirst()', () {
+ test('removes an element from the beginning of the queue', () {
var queue = QueueList.from([1, 2, 3]);
expect(queue.removeFirst(), equals(1));
expect(queue, equals([2, 3]));
});
test(
- "removes an element from the beginning of a queue with an internal "
- "gap", () {
+ 'removes an element from the beginning of a queue with an internal '
+ 'gap', () {
var queue = withInternalGap();
expect(queue.removeFirst(), equals(1));
expect(queue, equals([2, 3, 4, 5, 6, 7]));
});
- test("removes an element from the beginning of a queue at capacity", () {
+ test('removes an element from the beginning of a queue at capacity', () {
var queue = atCapacity();
expect(queue.removeFirst(), equals(1));
expect(queue, equals([2, 3, 4, 5, 6, 7]));
});
- test("throws a StateError for an empty queue", () {
+ test('throws a StateError for an empty queue', () {
expect(QueueList().removeFirst, throwsStateError);
});
});
- group("removeLast()", () {
- test("removes an element from the end of the queue", () {
+ group('removeLast()', () {
+ test('removes an element from the end of the queue', () {
var queue = QueueList.from([1, 2, 3]);
expect(queue.removeLast(), equals(3));
expect(queue, equals([1, 2]));
});
- test("removes an element from the end of a queue with an internal gap", () {
+ test('removes an element from the end of a queue with an internal gap', () {
var queue = withInternalGap();
expect(queue.removeLast(), equals(7));
expect(queue, equals([1, 2, 3, 4, 5, 6]));
});
- test("removes an element from the end of a queue at capacity", () {
+ test('removes an element from the end of a queue at capacity', () {
var queue = atCapacity();
expect(queue.removeLast(), equals(7));
expect(queue, equals([1, 2, 3, 4, 5, 6]));
});
- test("throws a StateError for an empty queue", () {
+ test('throws a StateError for an empty queue', () {
expect(QueueList().removeLast, throwsStateError);
});
});
- group("length", () {
- test("returns the length of a queue", () {
+ group('length', () {
+ test('returns the length of a queue', () {
expect(QueueList.from([1, 2, 3]).length, equals(3));
});
- test("returns the length of a queue with an internal gap", () {
+ test('returns the length of a queue with an internal gap', () {
expect(withInternalGap().length, equals(7));
});
- test("returns the length of a queue at capacity", () {
+ test('returns the length of a queue at capacity', () {
expect(atCapacity().length, equals(7));
});
});
- group("length=", () {
- test("shrinks a larger queue", () {
+ group('length=', () {
+ test('shrinks a larger queue', () {
var queue = QueueList.from([1, 2, 3]);
queue.length = 1;
expect(queue, equals([1]));
});
- test("grows a smaller queue", () {
+ test('grows a smaller queue', () {
var queue = QueueList.from([1, 2, 3]);
queue.length = 5;
expect(queue, equals([1, 2, 3, null, null]));
});
- test("throws a RangeError if length is less than 0", () {
+ test('throws a RangeError if length is less than 0', () {
expect(() => QueueList().length = -1, throwsRangeError);
});
});
- group("[]", () {
- test("returns individual entries in the queue", () {
+ group('[]', () {
+ test('returns individual entries in the queue', () {
var queue = QueueList.from([1, 2, 3]);
expect(queue[0], equals(1));
expect(queue[1], equals(2));
expect(queue[2], equals(3));
});
- test("returns individual entries in a queue with an internal gap", () {
+ test('returns individual entries in a queue with an internal gap', () {
var queue = withInternalGap();
expect(queue[0], equals(1));
expect(queue[1], equals(2));
@@ -165,41 +165,41 @@
expect(queue[6], equals(7));
});
- test("throws a RangeError if the index is less than 0", () {
+ test('throws a RangeError if the index is less than 0', () {
var queue = QueueList.from([1, 2, 3]);
expect(() => queue[-1], throwsRangeError);
});
test(
- "throws a RangeError if the index is greater than or equal to the "
- "length", () {
+ 'throws a RangeError if the index is greater than or equal to the '
+ 'length', () {
var queue = QueueList.from([1, 2, 3]);
expect(() => queue[3], throwsRangeError);
});
});
- group("[]=", () {
- test("sets individual entries in the queue", () {
+ group('[]=', () {
+ test('sets individual entries in the queue', () {
var queue = QueueList<dynamic>.from([1, 2, 3]);
- queue[0] = "a";
- queue[1] = "b";
- queue[2] = "c";
- expect(queue, equals(["a", "b", "c"]));
+ queue[0] = 'a';
+ queue[1] = 'b';
+ queue[2] = 'c';
+ expect(queue, equals(['a', 'b', 'c']));
});
- test("sets individual entries in a queue with an internal gap", () {
+ test('sets individual entries in a queue with an internal gap', () {
var queue = withInternalGap();
- queue[0] = "a";
- queue[1] = "b";
- queue[2] = "c";
- queue[3] = "d";
- queue[4] = "e";
- queue[5] = "f";
- queue[6] = "g";
- expect(queue, equals(["a", "b", "c", "d", "e", "f", "g"]));
+ queue[0] = 'a';
+ queue[1] = 'b';
+ queue[2] = 'c';
+ queue[3] = 'd';
+ queue[4] = 'e';
+ queue[5] = 'f';
+ queue[6] = 'g';
+ expect(queue, equals(['a', 'b', 'c', 'd', 'e', 'f', 'g']));
});
- test("throws a RangeError if the index is less than 0", () {
+ test('throws a RangeError if the index is less than 0', () {
var queue = QueueList.from([1, 2, 3]);
expect(() {
queue[-1] = 0;
@@ -207,8 +207,8 @@
});
test(
- "throws a RangeError if the index is greater than or equal to the "
- "length", () {
+ 'throws a RangeError if the index is greater than or equal to the '
+ 'length', () {
var queue = QueueList.from([1, 2, 3]);
expect(() {
queue[3] = 4;
@@ -216,44 +216,44 @@
});
});
- group("throws a modification error for", () {
+ group('throws a modification error for', () {
var queue;
setUp(() {
queue = QueueList.from([1, 2, 3]);
});
- test("add", () {
+ test('add', () {
expect(() => queue.forEach((_) => queue.add(4)),
throwsConcurrentModificationError);
});
- test("addAll", () {
+ test('addAll', () {
expect(() => queue.forEach((_) => queue.addAll([4, 5, 6])),
throwsConcurrentModificationError);
});
- test("addFirst", () {
+ test('addFirst', () {
expect(() => queue.forEach((_) => queue.addFirst(0)),
throwsConcurrentModificationError);
});
- test("removeFirst", () {
+ test('removeFirst', () {
expect(() => queue.forEach((_) => queue.removeFirst()),
throwsConcurrentModificationError);
});
- test("removeLast", () {
+ test('removeLast', () {
expect(() => queue.forEach((_) => queue.removeLast()),
throwsConcurrentModificationError);
});
- test("length=", () {
+ test('length=', () {
expect(() => queue.forEach((_) => queue.length = 1),
throwsConcurrentModificationError);
});
});
- test("cast does not throw on mutation when the type is valid", () {
+ test('cast does not throw on mutation when the type is valid', () {
var patternQueue = QueueList<Pattern>()..addAll(['a', 'b']);
var stringQueue = patternQueue.cast<String>();
stringQueue.addAll(['c', 'd']);
@@ -273,7 +273,7 @@
expect(patternQueue, stringQueue, reason: 'Should forward to original');
});
- test("cast throws on mutation when the type is not valid", () {
+ test('cast throws on mutation when the type is not valid', () {
QueueList<Object> stringQueue = QueueList<String>();
var numQueue = stringQueue.cast<num>();
expect(
@@ -289,7 +289,7 @@
);
});
- test("cast returns a new QueueList", () {
+ test('cast returns a new QueueList', () {
var queue = QueueList<String>();
expect(queue.cast<Pattern>(), isNot(same(queue)));
});
diff --git a/test/union_set_controller_test.dart b/test/union_set_controller_test.dart
index ff8c95a..8f5ad83 100644
--- a/test/union_set_controller_test.dart
+++ b/test/union_set_controller_test.dart
@@ -2,32 +2,32 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:test/test.dart";
+import 'package:test/test.dart';
-import "package:collection/collection.dart";
+import 'package:collection/collection.dart';
void main() {
UnionSetController<int> controller;
Set<int> innerSet;
setUp(() {
- innerSet = Set.from([1, 2, 3]);
+ innerSet = {1, 2, 3};
controller = UnionSetController()..add(innerSet);
});
- test("exposes a union set", () {
+ test('exposes a union set', () {
expect(controller.set, unorderedEquals([1, 2, 3]));
- controller.add(Set.from([3, 4, 5]));
+ controller.add({3, 4, 5});
expect(controller.set, unorderedEquals([1, 2, 3, 4, 5]));
controller.remove(innerSet);
expect(controller.set, unorderedEquals([3, 4, 5]));
});
- test("exposes a disjoint union set", () {
+ test('exposes a disjoint union set', () {
expect(controller.set, unorderedEquals([1, 2, 3]));
- controller.add(Set.from([4, 5, 6]));
+ controller.add({4, 5, 6});
expect(controller.set, unorderedEquals([1, 2, 3, 4, 5, 6]));
controller.remove(innerSet);
diff --git a/test/union_set_test.dart b/test/union_set_test.dart
index 6624e5f..795cf2b 100644
--- a/test/union_set_test.dart
+++ b/test/union_set_test.dart
@@ -2,34 +2,34 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:test/test.dart";
+import 'package:test/test.dart';
-import "package:collection/collection.dart";
+import 'package:collection/collection.dart';
void main() {
- group("with an empty outer set", () {
+ group('with an empty outer set', () {
var set;
setUp(() {
- set = UnionSet<int>(Set());
+ set = UnionSet<int>({});
});
- test("length returns 0", () {
+ test('length returns 0', () {
expect(set.length, equals(0));
});
- test("contains() returns false", () {
+ test('contains() returns false', () {
expect(set.contains(0), isFalse);
expect(set.contains(null), isFalse);
- expect(set.contains("foo"), isFalse);
+ expect(set.contains('foo'), isFalse);
});
- test("lookup() returns null", () {
+ test('lookup() returns null', () {
expect(set.lookup(0), isNull);
expect(set.lookup(null), isNull);
- expect(set.lookup("foo"), isNull);
+ expect(set.lookup('foo'), isNull);
});
- test("toSet() returns an empty set", () {
+ test('toSet() returns an empty set', () {
expect(set.toSet(), isEmpty);
expect(set.toSet(), isNot(same(set)));
});
@@ -39,105 +39,105 @@
});
});
- group("with multiple disjoint sets", () {
+ group('with multiple disjoint sets', () {
var set;
setUp(() {
set = UnionSet.from([
- Set.of([1, 2]),
- Set.of([3, 4]),
- Set.of([5]),
- Set()
+ {1, 2},
+ {3, 4},
+ {5},
+ <int>{},
], disjoint: true);
});
- test("length returns the total length", () {
+ test('length returns the total length', () {
expect(set.length, equals(5));
});
- test("contains() returns whether any set contains the element", () {
+ test('contains() returns whether any set contains the element', () {
expect(set.contains(1), isTrue);
expect(set.contains(4), isTrue);
expect(set.contains(5), isTrue);
expect(set.contains(6), isFalse);
});
- test("lookup() returns elements that are in any set", () {
+ test('lookup() returns elements that are in any set', () {
expect(set.lookup(1), equals(1));
expect(set.lookup(4), equals(4));
expect(set.lookup(5), equals(5));
expect(set.lookup(6), isNull);
});
- test("toSet() returns the union of all the sets", () {
+ test('toSet() returns the union of all the sets', () {
expect(set.toSet(), unorderedEquals([1, 2, 3, 4, 5]));
expect(set.toSet(), isNot(same(set)));
});
- test("map() maps the elements", () {
+ test('map() maps the elements', () {
expect(set.map((i) => i * 2), unorderedEquals([2, 4, 6, 8, 10]));
});
});
- group("with multiple overlapping sets", () {
+ group('with multiple overlapping sets', () {
var set;
setUp(() {
set = UnionSet.from([
- Set.of([1, 2, 3]),
- Set.of([3, 4]),
- Set.of([5, 1]),
- Set()
+ {1, 2, 3},
+ {3, 4},
+ {5, 1},
+ <int>{},
]);
});
- test("length returns the total length", () {
+ test('length returns the total length', () {
expect(set.length, equals(5));
});
- test("contains() returns whether any set contains the element", () {
+ test('contains() returns whether any set contains the element', () {
expect(set.contains(1), isTrue);
expect(set.contains(4), isTrue);
expect(set.contains(5), isTrue);
expect(set.contains(6), isFalse);
});
- test("lookup() returns elements that are in any set", () {
+ test('lookup() returns elements that are in any set', () {
expect(set.lookup(1), equals(1));
expect(set.lookup(4), equals(4));
expect(set.lookup(5), equals(5));
expect(set.lookup(6), isNull);
});
- test("lookup() returns the first element in an ordered context", () {
+ test('lookup() returns the first element in an ordered context', () {
var duration1 = Duration(seconds: 0);
var duration2 = Duration(seconds: 0);
expect(duration1, equals(duration2));
expect(duration1, isNot(same(duration2)));
var set = UnionSet.from([
- Set.of([duration1]),
- Set.of([duration2])
+ {duration1},
+ {duration2}
]);
expect(set.lookup(Duration(seconds: 0)), same(duration1));
});
- test("toSet() returns the union of all the sets", () {
+ test('toSet() returns the union of all the sets', () {
expect(set.toSet(), unorderedEquals([1, 2, 3, 4, 5]));
expect(set.toSet(), isNot(same(set)));
});
- test("map() maps the elements", () {
+ test('map() maps the elements', () {
expect(set.map((i) => i * 2), unorderedEquals([2, 4, 6, 8, 10]));
});
});
- group("after an inner set was modified", () {
+ group('after an inner set was modified', () {
var set;
setUp(() {
- var innerSet = Set.of([3, 7]);
+ var innerSet = {3, 7};
set = UnionSet.from([
- Set.of([1, 2]),
- Set.of([5]),
+ {1, 2},
+ {5},
innerSet
]);
@@ -145,19 +145,19 @@
innerSet.remove(7);
});
- test("length returns the total length", () {
+ test('length returns the total length', () {
expect(set.length, equals(5));
});
- test("contains() returns true for a new element", () {
+ test('contains() returns true for a new element', () {
expect(set.contains(4), isTrue);
});
- test("contains() returns false for a removed element", () {
+ test('contains() returns false for a removed element', () {
expect(set.contains(7), isFalse);
});
- test("lookup() returns a new element", () {
+ test('lookup() returns a new element', () {
expect(set.lookup(4), equals(4));
});
@@ -165,44 +165,44 @@
expect(set.lookup(7), isNull);
});
- test("toSet() returns the union of all the sets", () {
+ test('toSet() returns the union of all the sets', () {
expect(set.toSet(), unorderedEquals([1, 2, 3, 4, 5]));
expect(set.toSet(), isNot(same(set)));
});
- test("map() maps the elements", () {
+ test('map() maps the elements', () {
expect(set.map((i) => i * 2), unorderedEquals([2, 4, 6, 8, 10]));
});
});
- group("after the outer set was modified", () {
+ group('after the outer set was modified', () {
var set;
setUp(() {
- var innerSet = Set.of([6]);
- var outerSet = Set.of([
- Set.of([1, 2]),
- Set.of([5]),
+ var innerSet = {6};
+ var outerSet = {
+ {1, 2},
+ {5},
innerSet
- ]);
+ };
set = UnionSet<int>(outerSet);
outerSet.remove(innerSet);
- outerSet.add(Set.of([3, 4]));
+ outerSet.add({3, 4});
});
- test("length returns the total length", () {
+ test('length returns the total length', () {
expect(set.length, equals(5));
});
- test("contains() returns true for a new element", () {
+ test('contains() returns true for a new element', () {
expect(set.contains(4), isTrue);
});
- test("contains() returns false for a removed element", () {
+ test('contains() returns false for a removed element', () {
expect(set.contains(6), isFalse);
});
- test("lookup() returns a new element", () {
+ test('lookup() returns a new element', () {
expect(set.lookup(4), equals(4));
});
@@ -210,12 +210,12 @@
expect(set.lookup(6), isNull);
});
- test("toSet() returns the union of all the sets", () {
+ test('toSet() returns the union of all the sets', () {
expect(set.toSet(), unorderedEquals([1, 2, 3, 4, 5]));
expect(set.toSet(), isNot(same(set)));
});
- test("map() maps the elements", () {
+ test('map() maps the elements', () {
expect(set.map((i) => i * 2), unorderedEquals([2, 4, 6, 8, 10]));
});
});
diff --git a/test/unmodifiable_collection_test.dart b/test/unmodifiable_collection_test.dart
index dcc0f3b..a7abd89 100644
--- a/test/unmodifiable_collection_test.dart
+++ b/test/unmodifiable_collection_test.dart
@@ -2,53 +2,53 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:test/test.dart";
+import 'package:test/test.dart';
-import "package:collection/collection.dart";
+import 'package:collection/collection.dart';
// Test unmodifiable collection views.
// The collections should pass through the operations that are allowed,
// an throw on the ones that aren't without affecting the original.
-main() {
+void main() {
var list = <int>[];
- testUnmodifiableList(list, UnmodifiableListView(list), "empty");
+ testUnmodifiableList(list, UnmodifiableListView(list), 'empty');
list = [42];
- testUnmodifiableList(list, UnmodifiableListView(list), "single-42");
+ testUnmodifiableList(list, UnmodifiableListView(list), 'single-42');
list = [7];
- testUnmodifiableList(list, UnmodifiableListView(list), "single!42");
+ testUnmodifiableList(list, UnmodifiableListView(list), 'single!42');
list = [1, 42, 10];
- testUnmodifiableList(list, UnmodifiableListView(list), "three-42");
+ testUnmodifiableList(list, UnmodifiableListView(list), 'three-42');
list = [1, 7, 10];
- testUnmodifiableList(list, UnmodifiableListView(list), "three!42");
+ testUnmodifiableList(list, UnmodifiableListView(list), 'three!42');
list = [];
- testNonGrowableList(list, NonGrowableListView(list), "empty");
+ testNonGrowableList(list, NonGrowableListView(list), 'empty');
list = [42];
- testNonGrowableList(list, NonGrowableListView(list), "single-42");
+ testNonGrowableList(list, NonGrowableListView(list), 'single-42');
list = [7];
- testNonGrowableList(list, NonGrowableListView(list), "single!42");
+ testNonGrowableList(list, NonGrowableListView(list), 'single!42');
list = [1, 42, 10];
- testNonGrowableList(list, NonGrowableListView(list), "three-42");
+ testNonGrowableList(list, NonGrowableListView(list), 'three-42');
list = [1, 7, 10];
- testNonGrowableList(list, NonGrowableListView(list), "three!42");
+ testNonGrowableList(list, NonGrowableListView(list), 'three!42');
- var aSet = Set<int>();
- testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), "empty");
- aSet = Set();
- testUnmodifiableSet(aSet, const UnmodifiableSetView.empty(), "const empty");
- aSet = Set.of([42]);
- testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), "single-42");
- aSet = Set.of([7]);
- testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), "single!42");
- aSet = Set.of([1, 42, 10]);
- testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), "three-42");
- aSet = Set.of([1, 7, 10]);
- testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), "three!42");
+ var aSet = <int>{};
+ testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), 'empty');
+ aSet = {};
+ testUnmodifiableSet(aSet, const UnmodifiableSetView.empty(), 'const empty');
+ aSet = {42};
+ testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), 'single-42');
+ aSet = {7};
+ testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), 'single!42');
+ aSet = {1, 42, 10};
+ testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), 'three-42');
+ aSet = {1, 7, 10};
+ testUnmodifiableSet(aSet, UnmodifiableSetView(aSet), 'three!42');
}
void testUnmodifiableList(List<int> original, List<int> wrapped, String name) {
- name = "unmodifiable-list-$name";
+ name = 'unmodifiable-list-$name';
testIterable(original, wrapped, name);
testReadList(original, wrapped, name);
testNoWriteList(original, wrapped, name);
@@ -56,7 +56,7 @@
}
void testNonGrowableList(List<int> original, List<int> wrapped, String name) {
- name = "nongrowable-list-$name";
+ name = 'nongrowable-list-$name';
testIterable(original, wrapped, name);
testReadList(original, wrapped, name);
testWriteList(original, wrapped, name);
@@ -64,23 +64,23 @@
}
void testUnmodifiableSet(Set<int> original, Set<int> wrapped, String name) {
- name = "unmodifiable-set-$name";
+ name = 'unmodifiable-set-$name';
testIterable(original, wrapped, name);
testReadSet(original, wrapped, name);
testNoChangeSet(original, wrapped, name);
}
void testIterable(Iterable<int> original, Iterable<int> wrapped, String name) {
- test("$name - any", () {
+ test('$name - any', () {
expect(wrapped.any((x) => true), equals(original.any((x) => true)));
expect(wrapped.any((x) => false), equals(original.any((x) => false)));
});
- test("$name - contains", () {
+ test('$name - contains', () {
expect(wrapped.contains(0), equals(original.contains(0)));
});
- test("$name - elementAt", () {
+ test('$name - elementAt', () {
if (original.isEmpty) {
expect(() => wrapped.elementAt(0), throwsRangeError);
} else {
@@ -88,17 +88,17 @@
}
});
- test("$name - every", () {
+ test('$name - every', () {
expect(wrapped.every((x) => true), equals(original.every((x) => true)));
expect(wrapped.every((x) => false), equals(original.every((x) => false)));
});
- test("$name - expand", () {
+ test('$name - expand', () {
expect(
wrapped.expand((x) => [x, x]), equals(original.expand((x) => [x, x])));
});
- test("$name - first", () {
+ test('$name - first', () {
if (original.isEmpty) {
expect(() => wrapped.first, throwsStateError);
} else {
@@ -106,7 +106,7 @@
}
});
- test("$name - firstWhere", () {
+ test('$name - firstWhere', () {
if (original.isEmpty) {
expect(() => wrapped.firstWhere((_) => true), throwsStateError);
} else {
@@ -116,14 +116,14 @@
expect(() => wrapped.firstWhere((_) => false), throwsStateError);
});
- test("$name - fold", () {
+ test('$name - fold', () {
expect(wrapped.fold(0, (x, y) => x + y),
equals(original.fold(0, (x, y) => x + y)));
});
- test("$name - forEach", () {
- int wrapCtr = 0;
- int origCtr = 0;
+ test('$name - forEach', () {
+ var wrapCtr = 0;
+ var origCtr = 0;
wrapped.forEach((x) {
wrapCtr += x;
});
@@ -133,15 +133,15 @@
expect(wrapCtr, equals(origCtr));
});
- test("$name - isEmpty", () {
+ test('$name - isEmpty', () {
expect(wrapped.isEmpty, equals(original.isEmpty));
});
- test("$name - isNotEmpty", () {
+ test('$name - isNotEmpty', () {
expect(wrapped.isNotEmpty, equals(original.isNotEmpty));
});
- test("$name - iterator", () {
+ test('$name - iterator', () {
Iterator wrapIter = wrapped.iterator;
Iterator origIter = original.iterator;
while (origIter.moveNext()) {
@@ -151,12 +151,12 @@
expect(wrapIter.moveNext(), equals(false));
});
- test("$name - join", () {
- expect(wrapped.join(""), equals(original.join("")));
- expect(wrapped.join("-"), equals(original.join("-")));
+ test('$name - join', () {
+ expect(wrapped.join(''), equals(original.join('')));
+ expect(wrapped.join('-'), equals(original.join('-')));
});
- test("$name - last", () {
+ test('$name - last', () {
if (original.isEmpty) {
expect(() => wrapped.last, throwsStateError);
} else {
@@ -164,7 +164,7 @@
}
});
- test("$name - lastWhere", () {
+ test('$name - lastWhere', () {
if (original.isEmpty) {
expect(() => wrapped.lastWhere((_) => true), throwsStateError);
} else {
@@ -174,15 +174,15 @@
expect(() => wrapped.lastWhere((_) => false), throwsStateError);
});
- test("$name - length", () {
+ test('$name - length', () {
expect(wrapped.length, equals(original.length));
});
- test("$name - map", () {
- expect(wrapped.map((x) => "[$x]"), equals(original.map((x) => "[$x]")));
+ test('$name - map', () {
+ expect(wrapped.map((x) => '[$x]'), equals(original.map((x) => '[$x]')));
});
- test("$name - reduce", () {
+ test('$name - reduce', () {
if (original.isEmpty) {
expect(() => wrapped.reduce((x, y) => x + y), throwsStateError);
} else {
@@ -191,7 +191,7 @@
}
});
- test("$name - single", () {
+ test('$name - single', () {
if (original.length != 1) {
expect(() => wrapped.single, throwsStateError);
} else {
@@ -199,7 +199,7 @@
}
});
- test("$name - singleWhere", () {
+ test('$name - singleWhere', () {
if (original.length != 1) {
expect(() => wrapped.singleWhere((_) => true), throwsStateError);
} else {
@@ -209,13 +209,13 @@
expect(() => wrapped.singleWhere((_) => false), throwsStateError);
});
- test("$name - skip", () {
+ test('$name - skip', () {
expect(wrapped.skip(0), orderedEquals(original.skip(0)));
expect(wrapped.skip(1), orderedEquals(original.skip(1)));
expect(wrapped.skip(5), orderedEquals(original.skip(5)));
});
- test("$name - skipWhile", () {
+ test('$name - skipWhile', () {
expect(wrapped.skipWhile((x) => true),
orderedEquals(original.skipWhile((x) => true)));
expect(wrapped.skipWhile((x) => false),
@@ -224,13 +224,13 @@
orderedEquals(original.skipWhile((x) => x != 42)));
});
- test("$name - take", () {
+ test('$name - take', () {
expect(wrapped.take(0), orderedEquals(original.take(0)));
expect(wrapped.take(1), orderedEquals(original.take(1)));
expect(wrapped.take(5), orderedEquals(original.take(5)));
});
- test("$name - takeWhile", () {
+ test('$name - takeWhile', () {
expect(wrapped.takeWhile((x) => true),
orderedEquals(original.takeWhile((x) => true)));
expect(wrapped.takeWhile((x) => false),
@@ -239,17 +239,17 @@
orderedEquals(original.takeWhile((x) => x != 42)));
});
- test("$name - toList", () {
+ test('$name - toList', () {
expect(wrapped.toList(), orderedEquals(original.toList()));
expect(wrapped.toList(growable: false),
orderedEquals(original.toList(growable: false)));
});
- test("$name - toSet", () {
+ test('$name - toSet', () {
expect(wrapped.toSet(), unorderedEquals(original.toSet()));
});
- test("$name - where", () {
+ test('$name - where', () {
expect(
wrapped.where((x) => true), orderedEquals(original.where((x) => true)));
expect(wrapped.where((x) => false),
@@ -260,19 +260,19 @@
}
void testReadList(List original, List wrapped, String name) {
- test("$name - length", () {
+ test('$name - length', () {
expect(wrapped.length, equals(original.length));
});
- test("$name - isEmpty", () {
+ test('$name - isEmpty', () {
expect(wrapped.isEmpty, equals(original.isEmpty));
});
- test("$name - isNotEmpty", () {
+ test('$name - isNotEmpty', () {
expect(wrapped.isNotEmpty, equals(original.isNotEmpty));
});
- test("$name - []", () {
+ test('$name - []', () {
if (original.isEmpty) {
expect(() {
wrapped[0];
@@ -282,16 +282,16 @@
}
});
- test("$name - indexOf", () {
+ test('$name - indexOf', () {
expect(wrapped.indexOf(42), equals(original.indexOf(42)));
});
- test("$name - lastIndexOf", () {
+ test('$name - lastIndexOf', () {
expect(wrapped.lastIndexOf(42), equals(original.lastIndexOf(42)));
});
- test("$name - getRange", () {
- int len = original.length;
+ test('$name - getRange', () {
+ var len = original.length;
expect(wrapped.getRange(0, len), equals(original.getRange(0, len)));
expect(wrapped.getRange(len ~/ 2, len),
equals(original.getRange(len ~/ 2, len)));
@@ -299,14 +299,14 @@
wrapped.getRange(0, len ~/ 2), equals(original.getRange(0, len ~/ 2)));
});
- test("$name - sublist", () {
- int len = original.length;
+ test('$name - sublist', () {
+ var len = original.length;
expect(wrapped.sublist(0), equals(original.sublist(0)));
expect(wrapped.sublist(len ~/ 2), equals(original.sublist(len ~/ 2)));
expect(wrapped.sublist(0, len ~/ 2), equals(original.sublist(0, len ~/ 2)));
});
- test("$name - asMap", () {
+ test('$name - asMap', () {
expect(wrapped.asMap(), equals(original.asMap()));
});
}
@@ -314,7 +314,7 @@
void testNoWriteList(List<int> original, List<int> wrapped, String name) {
var copy = List.of(original);
- testThrows(name, thunk) {
+ void testThrows(name, thunk) {
test(name, () {
expect(thunk, throwsUnsupportedError);
// No modifications happened.
@@ -322,24 +322,24 @@
});
}
- testThrows("$name - []= throws", () {
+ testThrows('$name - []= throws', () {
wrapped[0] = 42;
});
- testThrows("$name - sort throws", () {
+ testThrows('$name - sort throws', () {
wrapped.sort();
});
- testThrows("$name - fillRange throws", () {
+ testThrows('$name - fillRange throws', () {
wrapped.fillRange(0, wrapped.length, 42);
});
- testThrows("$name - setRange throws", () {
+ testThrows('$name - setRange throws', () {
wrapped.setRange(
0, wrapped.length, Iterable.generate(wrapped.length, (i) => i));
});
- testThrows("$name - setAll throws", () {
+ testThrows('$name - setAll throws', () {
wrapped.setAll(0, Iterable.generate(wrapped.length, (i) => i));
});
}
@@ -347,9 +347,9 @@
void testWriteList(List<int> original, List wrapped, String name) {
var copy = List.of(original);
- test("$name - []=", () {
+ test('$name - []=', () {
if (original.isNotEmpty) {
- int originalFirst = original[0];
+ var originalFirst = original[0];
wrapped[0] = originalFirst + 1;
expect(original[0], equals(originalFirst + 1));
original[0] = originalFirst;
@@ -360,30 +360,30 @@
}
});
- test("$name - sort", () {
- List sortCopy = List.of(original);
+ test('$name - sort', () {
+ var sortCopy = List.of(original);
sortCopy.sort();
wrapped.sort();
expect(original, orderedEquals(sortCopy));
original.setAll(0, copy);
});
- test("$name - fillRange", () {
+ test('$name - fillRange', () {
wrapped.fillRange(0, wrapped.length, 37);
- for (int i = 0; i < original.length; i++) {
+ for (var i = 0; i < original.length; i++) {
expect(original[i], equals(37));
}
original.setAll(0, copy);
});
- test("$name - setRange", () {
+ test('$name - setRange', () {
List reverseList = original.reversed.toList();
wrapped.setRange(0, wrapped.length, reverseList);
expect(original, equals(reverseList));
original.setAll(0, copy);
});
- test("$name - setAll", () {
+ test('$name - setAll', () {
List reverseList = original.reversed.toList();
wrapped.setAll(0, reverseList);
expect(original, equals(reverseList));
@@ -403,55 +403,55 @@
});
}
- testThrows("$name - length= throws", () {
+ testThrows('$name - length= throws', () {
wrapped.length = 100;
});
- testThrows("$name - add throws", () {
+ testThrows('$name - add throws', () {
wrapped.add(42);
});
- testThrows("$name - addAll throws", () {
+ testThrows('$name - addAll throws', () {
wrapped.addAll([42]);
});
- testThrows("$name - insert throws", () {
+ testThrows('$name - insert throws', () {
wrapped.insert(0, 42);
});
- testThrows("$name - insertAll throws", () {
+ testThrows('$name - insertAll throws', () {
wrapped.insertAll(0, [42]);
});
- testThrows("$name - remove throws", () {
+ testThrows('$name - remove throws', () {
wrapped.remove(42);
});
- testThrows("$name - removeAt throws", () {
+ testThrows('$name - removeAt throws', () {
wrapped.removeAt(0);
});
- testThrows("$name - removeLast throws", () {
+ testThrows('$name - removeLast throws', () {
wrapped.removeLast();
});
- testThrows("$name - removeWhere throws", () {
+ testThrows('$name - removeWhere throws', () {
wrapped.removeWhere((element) => false);
});
- testThrows("$name - retainWhere throws", () {
+ testThrows('$name - retainWhere throws', () {
wrapped.retainWhere((element) => true);
});
- testThrows("$name - removeRange throws", () {
+ testThrows('$name - removeRange throws', () {
wrapped.removeRange(0, wrapped.length);
});
- testThrows("$name - replaceRange throws", () {
+ testThrows('$name - replaceRange throws', () {
wrapped.replaceRange(0, wrapped.length, [42]);
});
- testThrows("$name - clear throws", () {
+ testThrows('$name - clear throws', () {
wrapped.clear();
});
}
@@ -459,38 +459,37 @@
void testReadSet(Set<int> original, Set<int> wrapped, String name) {
var copy = Set.of(original);
- test("$name - containsAll", () {
+ test('$name - containsAll', () {
expect(wrapped.containsAll(copy), isTrue);
expect(wrapped.containsAll(copy.toList()), isTrue);
expect(wrapped.containsAll([]), isTrue);
expect(wrapped.containsAll([42]), equals(original.containsAll([42])));
});
- test("$name - intersection", () {
- expect(wrapped.intersection(Set()), isEmpty);
+ test('$name - intersection', () {
+ expect(wrapped.intersection({}), isEmpty);
expect(wrapped.intersection(copy), unorderedEquals(original));
- expect(wrapped.intersection(Set.of([42])),
- Set.of(original.contains(42) ? [42] : []));
+ expect(
+ wrapped.intersection({42}), Set.of(original.contains(42) ? [42] : []));
});
- test("$name - union", () {
- expect(wrapped.union(Set()), unorderedEquals(original));
+ test('$name - union', () {
+ expect(wrapped.union({}), unorderedEquals(original));
expect(wrapped.union(copy), unorderedEquals(original));
- expect(wrapped.union(Set.of([42])), equals(original.union(Set.of([42]))));
+ expect(wrapped.union({42}), equals(original.union({42})));
});
- test("$name - difference", () {
- expect(wrapped.difference(Set()), unorderedEquals(original));
+ test('$name - difference', () {
+ expect(wrapped.difference({}), unorderedEquals(original));
expect(wrapped.difference(copy), isEmpty);
- expect(wrapped.difference(Set.of([42])),
- equals(original.difference(Set.of([42]))));
+ expect(wrapped.difference({42}), equals(original.difference({42})));
});
}
void testNoChangeSet(Set<int> original, Set<int> wrapped, String name) {
var originalElements = original.toList();
- testThrows(name, thunk) {
+ void testThrows(name, thunk) {
test(name, () {
expect(thunk, throwsUnsupportedError);
// No modifications happened.
@@ -498,78 +497,78 @@
});
}
- testThrows("$name - add throws", () {
+ testThrows('$name - add throws', () {
wrapped.add(42);
});
- testThrows("$name - addAll throws", () {
+ testThrows('$name - addAll throws', () {
wrapped.addAll([42]);
});
- testThrows("$name - addAll empty throws", () {
+ testThrows('$name - addAll empty throws', () {
wrapped.addAll([]);
});
- testThrows("$name - remove throws", () {
+ testThrows('$name - remove throws', () {
wrapped.remove(42);
});
- testThrows("$name - removeAll throws", () {
+ testThrows('$name - removeAll throws', () {
wrapped.removeAll([42]);
});
- testThrows("$name - removeAll empty throws", () {
+ testThrows('$name - removeAll empty throws', () {
wrapped.removeAll([]);
});
- testThrows("$name - retainAll throws", () {
+ testThrows('$name - retainAll throws', () {
wrapped.retainAll([42]);
});
- testThrows("$name - removeWhere throws", () {
+ testThrows('$name - removeWhere throws', () {
wrapped.removeWhere((_) => false);
});
- testThrows("$name - retainWhere throws", () {
+ testThrows('$name - retainWhere throws', () {
wrapped.retainWhere((_) => true);
});
- testThrows("$name - clear throws", () {
+ testThrows('$name - clear throws', () {
wrapped.clear();
});
}
void testReadMap(Map<int, int> original, Map<int, int> wrapped, String name) {
- test("$name length", () {
+ test('$name length', () {
expect(wrapped.length, equals(original.length));
});
- test("$name isEmpty", () {
+ test('$name isEmpty', () {
expect(wrapped.isEmpty, equals(original.isEmpty));
});
- test("$name isNotEmpty", () {
+ test('$name isNotEmpty', () {
expect(wrapped.isNotEmpty, equals(original.isNotEmpty));
});
- test("$name operator[]", () {
+ test('$name operator[]', () {
expect(wrapped[0], equals(original[0]));
expect(wrapped[999], equals(original[999]));
});
- test("$name containsKey", () {
+ test('$name containsKey', () {
expect(wrapped.containsKey(0), equals(original.containsKey(0)));
expect(wrapped.containsKey(999), equals(original.containsKey(999)));
});
- test("$name containsValue", () {
+ test('$name containsValue', () {
expect(wrapped.containsValue(0), equals(original.containsValue(0)));
expect(wrapped.containsValue(999), equals(original.containsValue(999)));
});
- test("$name forEach", () {
- int origCnt = 0;
- int wrapCnt = 0;
+ test('$name forEach', () {
+ var origCnt = 0;
+ var wrapCnt = 0;
wrapped.forEach((k, v) {
wrapCnt += 1 << k + 3 * v;
});
@@ -579,19 +578,20 @@
expect(wrapCnt, equals(origCnt));
});
- test("$name keys", () {
+ test('$name keys', () {
expect(wrapped.keys, orderedEquals(original.keys));
});
- test("$name values", () {
+ test('$name values', () {
expect(wrapped.values, orderedEquals(original.values));
});
}
-testNoChangeMap(Map<int, int> original, Map<int, int> wrapped, String name) {
+void testNoChangeMap(
+ Map<int, int> original, Map<int, int> wrapped, String name) {
var copy = Map.of(original);
- testThrows(name, thunk) {
+ void testThrows(name, thunk) {
test(name, () {
expect(thunk, throwsUnsupportedError);
// No modifications happened.
@@ -599,27 +599,27 @@
});
}
- testThrows("$name operator[]= throws", () {
+ testThrows('$name operator[]= throws', () {
wrapped[0] = 42;
});
- testThrows("$name putIfAbsent throws", () {
+ testThrows('$name putIfAbsent throws', () {
wrapped.putIfAbsent(0, () => 42);
});
- testThrows("$name addAll throws", () {
- wrapped.addAll(Map()..[42] = 42);
+ testThrows('$name addAll throws', () {
+ wrapped.addAll({42: 42});
});
- testThrows("$name addAll empty throws", () {
- wrapped.addAll(Map());
+ testThrows('$name addAll empty throws', () {
+ wrapped.addAll({});
});
- testThrows("$name remove throws", () {
+ testThrows('$name remove throws', () {
wrapped.remove(0);
});
- testThrows("$name clear throws", () {
+ testThrows('$name clear throws', () {
wrapped.clear();
});
}
diff --git a/test/utils.dart b/test/utils.dart
index dbeadc7..48cd7cf 100644
--- a/test/utils.dart
+++ b/test/utils.dart
@@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import "package:test/test.dart";
+import 'package:test/test.dart';
final Matcher throwsCastError = throwsA(TypeMatcher<CastError>());
diff --git a/test/wrapper_test.dart b/test/wrapper_test.dart
index 3270def..43ff4c2 100644
--- a/test/wrapper_test.dart
+++ b/test/wrapper_test.dart
@@ -4,9 +4,10 @@
/// Tests wrapper utilities.
-import "dart:collection";
-import "package:collection/collection.dart";
-import "package:test/test.dart";
+import 'dart:collection';
+
+import 'package:collection/collection.dart';
+import 'package:test/test.dart';
// Test that any member access/call on the wrapper object is equal to
// an expected access on the wrapped object.
@@ -15,7 +16,7 @@
// Compare two Invocations for having equal type and arguments.
void testInvocations(Invocation i1, Invocation i2) {
- String name = "${i1.memberName}";
+ var name = '${i1.memberName}';
expect(i1.isGetter, equals(i2.isGetter), reason: name);
expect(i1.isSetter, equals(i2.isSetter), reason: name);
expect(i1.memberName, equals(i2.memberName), reason: name);
@@ -29,21 +30,23 @@
/// Use as `(expector..someAccess()).equals.someAccess();`.
/// Alle the intercepted member accesses returns `null`.
abstract class Expector {
- wrappedChecker(Invocation i);
+ dynamic wrappedChecker(Invocation i);
// After calling any member on the Expector, equals is an object that expects
// the *same* invocation on the wrapped object.
- var equals;
+ dynamic equals;
- noSuchMethod(Invocation i) {
+ @override
+ dynamic noSuchMethod(Invocation i) {
equals = wrappedChecker(i);
return null;
}
- toString() {
+ @override
+ String toString() {
// Cannot return an _Equals object since toString must return a String.
// Just set equals and return a string.
equals = wrappedChecker(toStringInvocation);
- return "";
+ return '';
}
}
@@ -52,14 +55,16 @@
class InvocationChecker {
final Invocation _expected;
InvocationChecker(this._expected);
- noSuchMethod(Invocation actual) {
+ @override
+ dynamic noSuchMethod(Invocation actual) {
testInvocations(_expected, actual);
return null;
}
- toString() {
+ @override
+ String toString() {
testInvocations(_expected, toStringInvocation);
- return "";
+ return '';
}
// Could also handle runtimeType, hashCode and == the same way as
// toString, but we are not testing them since collections generally
@@ -94,30 +99,36 @@
// Expector that wraps in DelegatingIterable.
class IterableExpector<T> extends Expector implements Iterable<T> {
- wrappedChecker(Invocation i) =>
+ @override
+ dynamic wrappedChecker(Invocation i) =>
DelegatingIterable<T>(IterableInvocationChecker<T>(i));
}
// Expector that wraps in DelegatingList.
class ListExpector<T> extends Expector implements List<T> {
- wrappedChecker(Invocation i) =>
+ @override
+ dynamic wrappedChecker(Invocation i) =>
DelegatingList<T>(ListInvocationChecker<T>(i));
}
// Expector that wraps in DelegatingSet.
class SetExpector<T> extends Expector implements Set<T> {
- wrappedChecker(Invocation i) => DelegatingSet<T>(SetInvocationChecker<T>(i));
+ @override
+ dynamic wrappedChecker(Invocation i) =>
+ DelegatingSet<T>(SetInvocationChecker<T>(i));
}
// Expector that wraps in DelegatingSet.
class QueueExpector<T> extends Expector implements Queue<T> {
- wrappedChecker(Invocation i) =>
+ @override
+ dynamic wrappedChecker(Invocation i) =>
DelegatingQueue<T>(QueueInvocationChecker<T>(i));
}
// Expector that wraps in DelegatingMap.
class MapExpector<K, V> extends Expector implements Map<K, V> {
- wrappedChecker(Invocation i) =>
+ @override
+ dynamic wrappedChecker(Invocation i) =>
DelegatingMap<K, V>(MapInvocationChecker<K, V>(i));
}
@@ -128,7 +139,7 @@
var val = Object();
void main() {
- testIterable(var expect) {
+ void testIterable(var expect) {
(expect..any(func1)).equals.any(func1);
(expect..contains(val)).equals.contains(val);
(expect..elementAt(0)).equals.elementAt(0);
@@ -149,7 +160,7 @@
(expect..isNotEmpty).equals.isNotEmpty;
(expect..iterator).equals.iterator;
(expect..join('')).equals.join();
- (expect..join("X")).equals.join("X");
+ (expect..join('X')).equals.join('X');
(expect..last).equals.last;
(expect..lastWhere(func1, orElse: null)).equals.lastWhere(func1);
(expect..lastWhere(func1, orElse: func0))
@@ -211,7 +222,7 @@
void testSet(var expect) {
testIterable(expect);
- Set set = Set();
+ var set = <dynamic>{};
(expect..add(val)).equals.add(val);
(expect..addAll([val])).equals.addAll([val]);
(expect..clear()).equals.clear();
@@ -239,7 +250,7 @@
}
void testMap(var expect) {
- Map map = Map();
+ var map = {};
(expect..[val]).equals[val];
(expect..[val] = val).equals[val] = val;
(expect..addAll(map)).equals.addAll(map);
@@ -260,373 +271,370 @@
// Runs tests of Set behavior.
//
// [setUpSet] should return a set with two elements: "foo" and "bar".
- void testTwoElementSet(Set<String> setUpSet()) {
- group("with two elements", () {
+ void testTwoElementSet(Set<String> Function() setUpSet) {
+ group('with two elements', () {
Set<String> set;
setUp(() => set = setUpSet());
- test(".any", () {
- expect(set.any((element) => element == "foo"), isTrue);
- expect(set.any((element) => element == "baz"), isFalse);
+ test('.any', () {
+ expect(set.any((element) => element == 'foo'), isTrue);
+ expect(set.any((element) => element == 'baz'), isFalse);
});
- test(".elementAt", () {
- expect(set.elementAt(0), equals("foo"));
- expect(set.elementAt(1), equals("bar"));
+ test('.elementAt', () {
+ expect(set.elementAt(0), equals('foo'));
+ expect(set.elementAt(1), equals('bar'));
expect(() => set.elementAt(2), throwsRangeError);
});
- test(".every", () {
- expect(set.every((element) => element == "foo"), isFalse);
+ test('.every', () {
+ expect(set.every((element) => element == 'foo'), isFalse);
expect(set.every((element) => element is String), isTrue);
});
- test(".expand", () {
+ test('.expand', () {
expect(set.expand((element) {
return [element.substring(0, 1), element.substring(1)];
- }), equals(["f", "oo", "b", "ar"]));
+ }), equals(['f', 'oo', 'b', 'ar']));
});
- test(".first", () {
- expect(set.first, equals("foo"));
+ test('.first', () {
+ expect(set.first, equals('foo'));
});
- test(".firstWhere", () {
- expect(set.firstWhere((element) => element is String), equals("foo"));
- expect(set.firstWhere((element) => element.startsWith("b")),
- equals("bar"));
+ test('.firstWhere', () {
+ expect(set.firstWhere((element) => element is String), equals('foo'));
+ expect(set.firstWhere((element) => element.startsWith('b')),
+ equals('bar'));
expect(() => set.firstWhere((element) => element is int),
throwsStateError);
- expect(set.firstWhere((element) => element is int, orElse: () => "baz"),
- equals("baz"));
+ expect(set.firstWhere((element) => element is int, orElse: () => 'baz'),
+ equals('baz'));
});
- test(".fold", () {
- expect(set.fold("start", (previous, element) => previous + element),
- equals("startfoobar"));
+ test('.fold', () {
+ expect(set.fold('start', (previous, element) => previous + element),
+ equals('startfoobar'));
});
- test(".forEach", () {
+ test('.forEach', () {
var values = [];
set.forEach(values.add);
- expect(values, equals(["foo", "bar"]));
+ expect(values, equals(['foo', 'bar']));
});
- test(".iterator", () {
+ test('.iterator', () {
var values = [];
for (var element in set) {
values.add(element);
}
- expect(values, equals(["foo", "bar"]));
+ expect(values, equals(['foo', 'bar']));
});
- test(".join", () {
- expect(set.join(", "), equals("foo, bar"));
+ test('.join', () {
+ expect(set.join(', '), equals('foo, bar'));
});
- test(".last", () {
- expect(set.last, equals("bar"));
+ test('.last', () {
+ expect(set.last, equals('bar'));
});
- test(".lastWhere", () {
- expect(set.lastWhere((element) => element is String), equals("bar"));
+ test('.lastWhere', () {
+ expect(set.lastWhere((element) => element is String), equals('bar'));
expect(
- set.lastWhere((element) => element.startsWith("f")), equals("foo"));
+ set.lastWhere((element) => element.startsWith('f')), equals('foo'));
expect(
() => set.lastWhere((element) => element is int), throwsStateError);
- expect(set.lastWhere((element) => element is int, orElse: () => "baz"),
- equals("baz"));
+ expect(set.lastWhere((element) => element is int, orElse: () => 'baz'),
+ equals('baz'));
});
- test(".map", () {
+ test('.map', () {
expect(
- set.map((element) => element.substring(1)), equals(["oo", "ar"]));
+ set.map((element) => element.substring(1)), equals(['oo', 'ar']));
});
- test(".reduce", () {
+ test('.reduce', () {
expect(set.reduce((previous, element) => previous + element),
- equals("foobar"));
+ equals('foobar'));
});
- test(".singleWhere", () {
- expect(() => set.singleWhere((element) => element == "baz"),
+ test('.singleWhere', () {
+ expect(() => set.singleWhere((element) => element == 'baz'),
throwsStateError);
- expect(set.singleWhere((element) => element == "foo"), "foo");
+ expect(set.singleWhere((element) => element == 'foo'), 'foo');
expect(() => set.singleWhere((element) => element is String),
throwsStateError);
});
- test(".skip", () {
- expect(set.skip(0), equals(["foo", "bar"]));
- expect(set.skip(1), equals(["bar"]));
+ test('.skip', () {
+ expect(set.skip(0), equals(['foo', 'bar']));
+ expect(set.skip(1), equals(['bar']));
expect(set.skip(2), equals([]));
});
- test(".skipWhile", () {
- expect(set.skipWhile((element) => element.startsWith("f")),
- equals(["bar"]));
- expect(set.skipWhile((element) => element.startsWith("z")),
- equals(["foo", "bar"]));
+ test('.skipWhile', () {
+ expect(set.skipWhile((element) => element.startsWith('f')),
+ equals(['bar']));
+ expect(set.skipWhile((element) => element.startsWith('z')),
+ equals(['foo', 'bar']));
expect(set.skipWhile((element) => element is String), equals([]));
});
- test(".take", () {
+ test('.take', () {
expect(set.take(0), equals([]));
- expect(set.take(1), equals(["foo"]));
- expect(set.take(2), equals(["foo", "bar"]));
+ expect(set.take(1), equals(['foo']));
+ expect(set.take(2), equals(['foo', 'bar']));
});
- test(".takeWhile", () {
- expect(set.takeWhile((element) => element.startsWith("f")),
- equals(["foo"]));
- expect(set.takeWhile((element) => element.startsWith("z")), equals([]));
+ test('.takeWhile', () {
+ expect(set.takeWhile((element) => element.startsWith('f')),
+ equals(['foo']));
+ expect(set.takeWhile((element) => element.startsWith('z')), equals([]));
expect(set.takeWhile((element) => element is String),
- equals(["foo", "bar"]));
+ equals(['foo', 'bar']));
});
- test(".toList", () {
- expect(set.toList(), equals(["foo", "bar"]));
- expect(() => set.toList(growable: false).add("baz"),
+ test('.toList', () {
+ expect(set.toList(), equals(['foo', 'bar']));
+ expect(() => set.toList(growable: false).add('baz'),
throwsUnsupportedError);
- expect(set.toList()..add("baz"), equals(["foo", "bar", "baz"]));
+ expect(set.toList()..add('baz'), equals(['foo', 'bar', 'baz']));
});
- test(".toSet", () {
- expect(set.toSet(), equals(Set.from(["foo", "bar"])));
+ test('.toSet', () {
+ expect(set.toSet(), equals({'foo', 'bar'}));
});
- test(".where", () {
+ test('.where', () {
expect(
- set.where((element) => element.startsWith("f")), equals(["foo"]));
- expect(set.where((element) => element.startsWith("z")), equals([]));
- expect(set.whereType<String>(), equals(["foo", "bar"]));
+ set.where((element) => element.startsWith('f')), equals(['foo']));
+ expect(set.where((element) => element.startsWith('z')), equals([]));
+ expect(set.whereType<String>(), equals(['foo', 'bar']));
});
- test(".containsAll", () {
- expect(set.containsAll(["foo", "bar"]), isTrue);
- expect(set.containsAll(["foo"]), isTrue);
- expect(set.containsAll(["foo", "bar", "qux"]), isFalse);
+ test('.containsAll', () {
+ expect(set.containsAll(['foo', 'bar']), isTrue);
+ expect(set.containsAll(['foo']), isTrue);
+ expect(set.containsAll(['foo', 'bar', 'qux']), isFalse);
});
- test(".difference", () {
- expect(set.difference(Set.from(["foo", "baz"])),
- equals(Set.from(["bar"])));
+ test('.difference', () {
+ expect(set.difference({'foo', 'baz'}), equals({'bar'}));
});
- test(".intersection", () {
- expect(set.intersection(Set.from(["foo", "baz"])),
- equals(Set.from(["foo"])));
+ test('.intersection', () {
+ expect(set.intersection({'foo', 'baz'}), equals({'foo'}));
});
- test(".union", () {
- expect(set.union(Set.from(["foo", "baz"])),
- equals(Set.from(["foo", "bar", "baz"])));
+ test('.union', () {
+ expect(set.union({'foo', 'baz'}), equals({'foo', 'bar', 'baz'}));
});
});
}
- test("Iterable", () {
+ test('Iterable', () {
testIterable(IterableExpector());
});
- test("List", () {
+ test('List', () {
testList(ListExpector());
});
- test("Set", () {
+ test('Set', () {
testSet(SetExpector());
});
- test("Queue", () {
+ test('Queue', () {
testQueue(QueueExpector());
});
- test("Map", () {
+ test('Map', () {
testMap(MapExpector());
});
- group("MapKeySet", () {
+ group('MapKeySet', () {
Map<String, dynamic> map;
Set<String> set;
setUp(() {
- map = Map<String, int>();
+ map = <String, int>{};
set = MapKeySet<String>(map);
});
testTwoElementSet(() {
- map["foo"] = 1;
- map["bar"] = 2;
+ map['foo'] = 1;
+ map['bar'] = 2;
return set;
});
- test(".single", () {
+ test('.single', () {
expect(() => set.single, throwsStateError);
- map["foo"] = 1;
- expect(set.single, equals("foo"));
- map["bar"] = 1;
+ map['foo'] = 1;
+ expect(set.single, equals('foo'));
+ map['bar'] = 1;
expect(() => set.single, throwsStateError);
});
- test(".toString", () {
- expect(set.toString(), equals("{}"));
- map["foo"] = 1;
- map["bar"] = 2;
- expect(set.toString(), equals("{foo, bar}"));
+ test('.toString', () {
+ expect(set.toString(), equals('{}'));
+ map['foo'] = 1;
+ map['bar'] = 2;
+ expect(set.toString(), equals('{foo, bar}'));
});
- test(".contains", () {
- expect(set.contains("foo"), isFalse);
- map["foo"] = 1;
- expect(set.contains("foo"), isTrue);
+ test('.contains', () {
+ expect(set.contains('foo'), isFalse);
+ map['foo'] = 1;
+ expect(set.contains('foo'), isTrue);
});
- test(".isEmpty", () {
+ test('.isEmpty', () {
expect(set.isEmpty, isTrue);
- map["foo"] = 1;
+ map['foo'] = 1;
expect(set.isEmpty, isFalse);
});
- test(".isNotEmpty", () {
+ test('.isNotEmpty', () {
expect(set.isNotEmpty, isFalse);
- map["foo"] = 1;
+ map['foo'] = 1;
expect(set.isNotEmpty, isTrue);
});
- test(".length", () {
+ test('.length', () {
expect(set, hasLength(0));
- map["foo"] = 1;
+ map['foo'] = 1;
expect(set, hasLength(1));
- map["bar"] = 2;
+ map['bar'] = 2;
expect(set, hasLength(2));
});
- test("is unmodifiable", () {
- expect(() => set.add("baz"), throwsUnsupportedError);
- expect(() => set.addAll(["baz", "bang"]), throwsUnsupportedError);
- expect(() => set.remove("foo"), throwsUnsupportedError);
- expect(() => set.removeAll(["baz", "bang"]), throwsUnsupportedError);
- expect(() => set.retainAll(["foo"]), throwsUnsupportedError);
+ test('is unmodifiable', () {
+ expect(() => set.add('baz'), throwsUnsupportedError);
+ expect(() => set.addAll(['baz', 'bang']), throwsUnsupportedError);
+ expect(() => set.remove('foo'), throwsUnsupportedError);
+ expect(() => set.removeAll(['baz', 'bang']), throwsUnsupportedError);
+ expect(() => set.retainAll(['foo']), throwsUnsupportedError);
expect(() => set.removeWhere((_) => true), throwsUnsupportedError);
expect(() => set.retainWhere((_) => true), throwsUnsupportedError);
expect(() => set.clear(), throwsUnsupportedError);
});
});
- group("MapValueSet", () {
+ group('MapValueSet', () {
Map<String, String> map;
Set<String> set;
setUp(() {
- map = Map<String, String>();
+ map = <String, String>{};
set =
MapValueSet<String, String>(map, (string) => string.substring(0, 1));
});
testTwoElementSet(() {
- map["f"] = "foo";
- map["b"] = "bar";
+ map['f'] = 'foo';
+ map['b'] = 'bar';
return set;
});
- test(".single", () {
+ test('.single', () {
expect(() => set.single, throwsStateError);
- map["f"] = "foo";
- expect(set.single, equals("foo"));
- map["b"] = "bar";
+ map['f'] = 'foo';
+ expect(set.single, equals('foo'));
+ map['b'] = 'bar';
expect(() => set.single, throwsStateError);
});
- test(".toString", () {
- expect(set.toString(), equals("{}"));
- map["f"] = "foo";
- map["b"] = "bar";
- expect(set.toString(), equals("{foo, bar}"));
+ test('.toString', () {
+ expect(set.toString(), equals('{}'));
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ expect(set.toString(), equals('{foo, bar}'));
});
- test(".contains", () {
- expect(set.contains("foo"), isFalse);
- map["f"] = "foo";
- expect(set.contains("foo"), isTrue);
- expect(set.contains("fblthp"), isTrue);
+ test('.contains', () {
+ expect(set.contains('foo'), isFalse);
+ map['f'] = 'foo';
+ expect(set.contains('foo'), isTrue);
+ expect(set.contains('fblthp'), isTrue);
});
- test(".isEmpty", () {
+ test('.isEmpty', () {
expect(set.isEmpty, isTrue);
- map["f"] = "foo";
+ map['f'] = 'foo';
expect(set.isEmpty, isFalse);
});
- test(".isNotEmpty", () {
+ test('.isNotEmpty', () {
expect(set.isNotEmpty, isFalse);
- map["f"] = "foo";
+ map['f'] = 'foo';
expect(set.isNotEmpty, isTrue);
});
- test(".length", () {
+ test('.length', () {
expect(set, hasLength(0));
- map["f"] = "foo";
+ map['f'] = 'foo';
expect(set, hasLength(1));
- map["b"] = "bar";
+ map['b'] = 'bar';
expect(set, hasLength(2));
});
- test(".lookup", () {
- map["f"] = "foo";
- expect(set.lookup("fblthp"), equals("foo"));
- expect(set.lookup("bar"), isNull);
+ test('.lookup', () {
+ map['f'] = 'foo';
+ expect(set.lookup('fblthp'), equals('foo'));
+ expect(set.lookup('bar'), isNull);
});
- test(".add", () {
- set.add("foo");
- set.add("bar");
- expect(map, equals({"f": "foo", "b": "bar"}));
+ test('.add', () {
+ set.add('foo');
+ set.add('bar');
+ expect(map, equals({'f': 'foo', 'b': 'bar'}));
});
- test(".addAll", () {
- set.addAll(["foo", "bar"]);
- expect(map, equals({"f": "foo", "b": "bar"}));
+ test('.addAll', () {
+ set.addAll(['foo', 'bar']);
+ expect(map, equals({'f': 'foo', 'b': 'bar'}));
});
- test(".clear", () {
- map["f"] = "foo";
- map["b"] = "bar";
+ test('.clear', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
set.clear();
expect(map, isEmpty);
});
- test(".remove", () {
- map["f"] = "foo";
- map["b"] = "bar";
- set.remove("fblthp");
- expect(map, equals({"b": "bar"}));
+ test('.remove', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ set.remove('fblthp');
+ expect(map, equals({'b': 'bar'}));
});
- test(".removeAll", () {
- map["f"] = "foo";
- map["b"] = "bar";
- map["q"] = "qux";
- set.removeAll(["fblthp", "qux"]);
- expect(map, equals({"b": "bar"}));
+ test('.removeAll', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ map['q'] = 'qux';
+ set.removeAll(['fblthp', 'qux']);
+ expect(map, equals({'b': 'bar'}));
});
- test(".removeWhere", () {
- map["f"] = "foo";
- map["b"] = "bar";
- map["q"] = "qoo";
- set.removeWhere((element) => element.endsWith("o"));
- expect(map, equals({"b": "bar"}));
+ test('.removeWhere', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ map['q'] = 'qoo';
+ set.removeWhere((element) => element.endsWith('o'));
+ expect(map, equals({'b': 'bar'}));
});
- test(".retainAll", () {
- map["f"] = "foo";
- map["b"] = "bar";
- map["q"] = "qux";
- set.retainAll(["fblthp", "qux"]);
- expect(map, equals({"f": "foo", "q": "qux"}));
+ test('.retainAll', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ map['q'] = 'qux';
+ set.retainAll(['fblthp', 'qux']);
+ expect(map, equals({'f': 'foo', 'q': 'qux'}));
});
- test(".retainAll respects an unusual notion of equality", () {
+ test('.retainAll respects an unusual notion of equality', () {
map = HashMap<String, String>(
equals: (value1, value2) =>
value1.toLowerCase() == value2.toLowerCase(),
@@ -634,19 +642,19 @@
set =
MapValueSet<String, String>(map, (string) => string.substring(0, 1));
- map["f"] = "foo";
- map["B"] = "bar";
- map["Q"] = "qux";
- set.retainAll(["fblthp", "qux"]);
- expect(map, equals({"f": "foo", "Q": "qux"}));
+ map['f'] = 'foo';
+ map['B'] = 'bar';
+ map['Q'] = 'qux';
+ set.retainAll(['fblthp', 'qux']);
+ expect(map, equals({'f': 'foo', 'Q': 'qux'}));
});
- test(".retainWhere", () {
- map["f"] = "foo";
- map["b"] = "bar";
- map["q"] = "qoo";
- set.retainWhere((element) => element.endsWith("o"));
- expect(map, equals({"f": "foo", "q": "qoo"}));
+ test('.retainWhere', () {
+ map['f'] = 'foo';
+ map['b'] = 'bar';
+ map['q'] = 'qoo';
+ set.retainWhere((element) => element.endsWith('o'));
+ expect(map, equals({'f': 'foo', 'q': 'qoo'}));
});
});
}