Migrate the corelib_2/ tests starting with "e" through "i".

Change-Id: I764d0457da85b2935e1d83309eab4c4b5b3ea000
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/126204
Commit-Queue: Bob Nystrom <rnystrom@google.com>
Reviewed-by: Lasse R.H. Nielsen <lrn@google.com>
Auto-Submit: Bob Nystrom <rnystrom@google.com>
This commit is contained in:
Robert Nystrom 2019-12-02 23:19:10 +00:00 committed by commit-bot@chromium.org
parent a4d799c402
commit 284f662022
77 changed files with 6669 additions and 2 deletions

View file

@ -21,7 +21,7 @@ abstract class Invocation {
* If the named arguments are omitted, they default to no named arguments.
*/
factory Invocation.method(
Symbol memberName, Iterable<Object?> positionalArguments,
Symbol memberName, Iterable<Object?>? positionalArguments,
[Map<Symbol, Object?>? namedArguments]) =>
_Invocation.method(memberName, null, positionalArguments, namedArguments);
@ -35,7 +35,7 @@ abstract class Invocation {
* If the named arguments are omitted, they default to no named arguments.
*/
factory Invocation.genericMethod(Symbol memberName,
Iterable<Type> typeArguments, Iterable<Object?> positionalArguments,
Iterable<Type>? typeArguments, Iterable<Object?>? positionalArguments,
[Map<Symbol, Object?>? namedArguments]) =>
_Invocation.method(
memberName, typeArguments, positionalArguments, namedArguments);

View file

@ -0,0 +1,40 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
class A {
static Aa() => Ab();
static Ab() => Ac();
static Ac() => throw "abc";
}
class B {
static Ba() => Bb();
static Bb() => Bc();
static Bc() {
try {
A.Aa();
} catch (e) {
// This should produce a NoSuchMethodError.
var trace = e.stackTrace;
}
}
}
main() {
bool hasThrown = false;
try {
B.Ba();
} catch (e, stackTrace) {
hasThrown = true;
var trace = stackTrace.toString();
print(trace);
Expect.isTrue(trace.contains("Bc"));
Expect.isTrue(trace.contains("Bb"));
Expect.isTrue(trace.contains("Ba"));
Expect.isTrue(trace.contains("main"));
}
Expect.isTrue(hasThrown);
}

View file

@ -0,0 +1,29 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
class A {
get foo => cyclicStatic;
}
var a = new A();
dynamic cyclicStatic = (() => a.foo + 1)();
cyclicInitialization() {
return cyclicStatic;
}
main() {
bool hasThrown = false;
try {
cyclicStatic + 1;
} catch (e2) {
var e = e2;
hasThrown = true;
Expect.isTrue(
e.stackTrace is StackTrace, "$e doesn't have a non-null stack trace");
}
Expect.isTrue(hasThrown);
}

View file

@ -0,0 +1,68 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
void argument() {
throw new ArgumentError(499);
}
// Verify that
void noSuchMethod() {
(499 as dynamic).doesNotExist();
}
void nullThrown() {
throw null as dynamic;
}
void range() {
throw new RangeError.range(0, 1, 2);
}
abstract class A {
foo();
}
void unsupported() {
throw new UnsupportedError("unsupported");
}
void unimplemented() {
throw new UnimplementedError("unimplemented");
}
void state() {
[1, 2].single;
}
void cast() {
dynamic d = 1;
d as String;
}
main() {
List<Function> errorFunctions = [
argument,
noSuchMethod,
nullThrown, //# nullThrown: ok
range,
unsupported,
unimplemented,
state,
cast,
];
for (var f in errorFunctions) {
bool hasThrown = false;
try {
f();
} catch (e) {
hasThrown = true;
Expect.isTrue(
e.stackTrace is StackTrace, "$e doesn't have a non-null stack trace");
}
Expect.isTrue(hasThrown);
}
}

View file

@ -0,0 +1,77 @@
// 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.
import "package:expect/expect.dart";
// Test that error constructors do what they are documented as doing.
main() {
Expect.equals("Invalid argument(s)", new ArgumentError().toString());
Expect.equals(
"Invalid argument(s): message", new ArgumentError("message").toString());
Expect.equals(
"Invalid argument: null", new ArgumentError.value(null).toString());
Expect.equals("Invalid argument: 42", new ArgumentError.value(42).toString());
Expect.equals(
"Invalid argument: \"bad\"", new ArgumentError.value("bad").toString());
Expect.equals("Invalid argument (foo): null",
new ArgumentError.value(null, "foo").toString());
Expect.equals("Invalid argument (foo): 42",
new ArgumentError.value(42, "foo").toString());
Expect.equals("Invalid argument (foo): message: 42",
new ArgumentError.value(42, "foo", "message").toString());
Expect.equals("Invalid argument: message: 42",
new ArgumentError.value(42, null, "message").toString());
Expect.equals("Invalid argument(s): Must not be null",
new ArgumentError.notNull().toString());
Expect.equals("Invalid argument(s) (foo): Must not be null",
new ArgumentError.notNull("foo").toString());
Expect.equals("RangeError", new RangeError(null).toString());
Expect.equals("RangeError: message", new RangeError("message").toString());
Expect.equals("RangeError: Value not in range: 42",
new RangeError.value(42).toString());
Expect.equals("RangeError (foo): Value not in range: 42",
new RangeError.value(42, "foo").toString());
Expect.equals("RangeError (foo): message: 42",
new RangeError.value(42, "foo", "message").toString());
Expect.equals("RangeError: message: 42",
new RangeError.value(42, null, "message").toString());
Expect.equals("RangeError: Invalid value: Not in range 2..9, inclusive: 42",
new RangeError.range(42, 2, 9).toString());
Expect.equals(
"RangeError (foo): Invalid value: Not in range 2..9, "
"inclusive: 42",
new RangeError.range(42, 2, 9, "foo").toString());
Expect.equals("RangeError (foo): message: Not in range 2..9, inclusive: 42",
new RangeError.range(42, 2, 9, "foo", "message").toString());
Expect.equals("RangeError: message: Not in range 2..9, inclusive: 42",
new RangeError.range(42, 2, 9, null, "message").toString());
Expect.equals(
"RangeError: Index out of range: "
"index should be less than 3: 42",
new RangeError.index(42, [1, 2, 3]).toString());
Expect.equals(
"RangeError (foo): Index out of range: "
"index should be less than 3: 42",
new RangeError.index(42, [1, 2, 3], "foo").toString());
Expect.equals(
"RangeError (foo): message: "
"index should be less than 3: 42",
new RangeError.index(42, [1, 2, 3], "foo", "message").toString());
Expect.equals(
"RangeError: message: "
"index should be less than 3: 42",
new RangeError.index(42, [1, 2, 3], null, "message").toString());
Expect.equals(
"RangeError (foo): message: "
"index should be less than 2: 42",
new RangeError.index(42, [1, 2, 3], "foo", "message", 2).toString());
Expect.equals(
"RangeError: Index out of range: "
"index must not be negative: -5",
new RangeError.index(-5, [1, 2, 3]).toString());
}

View file

@ -0,0 +1,18 @@
// Copyright (c) 2011, 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.
library exception_implementation_test;
import "package:expect/expect.dart";
main() {
final msg = 1;
try {
throw new Exception(msg);
Expect.fail("Unreachable");
} on Exception catch (e) {
Expect.isTrue(e is Exception);
Expect.equals("Exception: $msg", e.toString());
}
}

View file

@ -0,0 +1,106 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
class ExpandoTest {
static Expando<int> visits = Expando('visits');
static testMain() {
var legal = [
new Object(),
new List(),
[1, 2, 3],
const [1, 2, 3],
new Map(),
{'x': 1, 'y': 2},
const {'x': 1, 'y': 2},
new Expando(),
new Expando('horse')
];
for (var object in legal) {
testNamedExpando(object);
testUnnamedExpando(object);
}
for (var object in legal) {
Expect.equals(2, visits[object], "$object");
}
testIllegal();
testIdentity();
}
static visit(object) {
int count = visits[object]!;
count = (count == null) ? 1 : count + 1;
visits[object] = count;
}
static testNamedExpando(object) {
Expando<int> expando = new Expando<int>('myexpando');
Expect.equals('myexpando', expando.name);
Expect.isTrue(expando.toString().startsWith('Expando:myexpando'));
testExpando(expando, object);
}
static testUnnamedExpando(object) {
Expando<int> expando = new Expando<int>();
Expect.isNull(expando.name);
Expect.isTrue(expando.toString().startsWith('Expando:'));
testExpando(expando, object);
}
static testExpando(Expando<int> expando, object) {
visit(object);
Expect.isNull(expando[object]);
expando[object] = 42;
Expect.equals(42, expando[object]);
expando[object] = null;
Expect.isNull(expando[object]);
Expando<int> alternative = new Expando('myexpando');
Expect.isNull(alternative[object]);
alternative[object] = 87;
Expect.isNull(expando[object]);
expando[object] = 99;
Expect.equals(99, expando[object]);
Expect.equals(87, alternative[object]);
}
static testIllegal() {
Expando<int> expando = new Expando<int>();
Expect.throwsArgumentError(() => expando['string'], "'string'");
Expect.throwsArgumentError(() => expando[42], "42");
Expect.throwsArgumentError(() => expando[42.87], "42.87");
Expect.throwsArgumentError(() => expando[true], "true");
Expect.throwsArgumentError(() => expando[false], "false");
}
static testIdentity() {
// Expando only depends on identity of object.
Expando<int> expando = new Expando<int>();
var m1 = new Mutable(1);
var m2 = new Mutable(7);
var m3 = new Mutable(13);
expando[m1] = 42;
Expect.equals(42, expando[m1]);
m1.id = 37;
Expect.equals(42, expando[m1]);
expando[m2] = 37;
expando[m3] = 10;
m3.id = 1;
Expect.equals(42, expando[m1]);
Expect.equals(37, expando[m2]);
Expect.equals(10, expando[m3]);
}
}
main() => ExpandoTest.testMain();
class Mutable {
int id;
Mutable(this.id);
int get hashCode => id;
bool operator ==(other) => other is Mutable && other.id == id;
}

View file

@ -0,0 +1,117 @@
// Copyright (c) 2011, 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.
import "package:expect/expect.dart";
// Tests basic expressions. Does not attempt to validate the details of arithmetic, coercion, and
// so forth.
class ExpressionTest {
ExpressionTest() {}
int foo = -1;
static testMain() {
var test = new ExpressionTest();
test.testBinary();
test.testUnary();
test.testShifts();
test.testBitwise();
test.testIncrement();
test.testMangling();
}
testBinary() {
int x = 4, y = 2;
Expect.equals(6, x + y);
Expect.equals(2, x - y);
Expect.equals(8, x * y);
Expect.equals(2, x / y);
Expect.equals(0, x % y);
}
testUnary() {
int x = 4, y = 2, z = -5;
bool t = true, f = false;
Expect.equals(-4, -x);
Expect.equals(4, ~z);
Expect.equals(f, !t);
}
testShifts() {
int x = 4, y = 2;
Expect.equals(y, x >> 1);
Expect.equals(x, y << 1);
}
testBitwise() {
int x = 4, y = 2;
Expect.equals(6, (x | y));
Expect.equals(0, (x & y));
Expect.equals(6, (x ^ y));
}
int operator [](int index) {
return foo;
}
operator []=(int index, int value) {
foo = value;
}
testIncrement() {
int x = 4, a = x++;
Expect.equals(4, a);
Expect.equals(5, x);
Expect.equals(6, ++x);
Expect.equals(6, x++);
Expect.equals(7, x);
Expect.equals(6, --x);
Expect.equals(6, x--);
Expect.equals(5, x);
this.foo = 0;
Expect.equals(0, this.foo++);
Expect.equals(1, this.foo);
Expect.equals(2, ++this.foo);
Expect.equals(2, this.foo);
Expect.equals(2, this.foo--);
Expect.equals(1, this.foo);
Expect.equals(0, --this.foo);
Expect.equals(0, this.foo);
Expect.equals(0, this[0]++);
Expect.equals(1, this[0]);
Expect.equals(2, ++this[0]);
Expect.equals(2, this[0]);
Expect.equals(2, this[0]--);
Expect.equals(1, this[0]);
Expect.equals(0, --this[0]);
Expect.equals(0, this[0]);
int $0 = 42, $1 = 87, $2 = 117;
Expect.equals(42, $0++);
Expect.equals(43, $0);
Expect.equals(44, ++$0);
Expect.equals(88, $0 += $0);
Expect.equals(87, $1++);
Expect.equals(88, $1);
Expect.equals(89, ++$1);
Expect.equals(178, ($1 += $1));
Expect.equals(117, $2++);
Expect.equals(118, $2);
Expect.equals(119, ++$2);
}
void testMangling() {
int $0 = 42, $1 = 87, $2 = 117;
this[0] = 0;
Expect.equals(42, (this[0] += $0));
Expect.equals(129, (this[0] += $1));
Expect.equals(246, (this[0] += $2));
}
}
main() {
ExpressionTest.testMain();
}

View file

@ -0,0 +1,97 @@
// Copyright (c) 2011, 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.
import "package:expect/expect.dart";
class ForInTest {
static testMain() {
testSimple();
testBreak();
testContinue();
testClosure();
}
static Set<int> getSmallSet() {
Set<int> set = new Set<int>();
set.add(1);
set.add(2);
set.add(4);
return set;
}
static void testSimple() {
Set<int> set = getSmallSet();
int count = 0;
for (final i in set) {
count += i;
}
Expect.equals(7, count);
count = 0;
for (var i in set) {
count += i;
}
Expect.equals(7, count);
count = 0;
for (int i in set) {
count += i;
}
Expect.equals(7, count);
count = 0;
for (final int i in set) {
count += i;
}
Expect.equals(7, count);
count = 0;
int i = 0;
Expect.equals(false, set.contains(i)); // Used to test [i] after loop.
for (i in set) {
count += i;
}
Expect.equals(7, count);
Expect.equals(true, set.contains(i));
// The default implementation of [Set] preserves order.
Expect.equals(4, i);
}
static void testBreak() {
Set<int> set = getSmallSet();
int count = 0;
for (final i in set) {
if (i == 4) break;
count += i;
}
Expect.equals(true, count < 4);
}
static void testContinue() {
Set<int> set = getSmallSet();
int count = 0;
for (final i in set) {
if (i < 4) continue;
count += i;
}
Expect.equals(4, count);
}
static void testClosure() {
Set<int> set = getSmallSet();
List<Function> closures = [];
int index = 0;
for (var i in set) {
closures.add(() => i);
index++;
}
Expect.equals(index, set.length);
Expect.equals(7, closures[0]() + closures[1]() + closures[2]());
}
}
main() {
ForInTest.testMain();
}

View file

@ -0,0 +1,106 @@
// Copyright (c) 2011, 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.
library format_exception_test;
import "package:expect/expect.dart";
test(exn, message, source, offset, toString) {
Expect.equals(message, exn.message);
Expect.equals(source, exn.source);
Expect.equals(offset, exn.offset);
Expect.equals(toString, exn.toString());
}
main() {
var e;
e = new FormatException();
test(e, "", null, null, "FormatException");
e = new FormatException("");
test(e, "", null, null, "FormatException");
e = new FormatException("message");
test(e, "message", null, null, "FormatException: message");
e = new FormatException("message", "source");
test(e, "message", "source", null, "FormatException: message\nsource");
e = new FormatException("message", "source" * 25);
test(e, "message", "source" * 25, null,
"FormatException: message\n" + "source" * 12 + "sou...");
e = new FormatException("message", "source" * 25);
test(e, "message", "source" * 25, null,
"FormatException: message\n" + "source" * 12 + "sou...");
e = new FormatException("message", "s1\nsource\ns2");
test(e, "message", "s1\nsource\ns2", null,
"FormatException: message\n" + "s1\nsource\ns2");
var o = new Object();
e = new FormatException("message", o, 10);
test(e, "message", o, 10, "FormatException: message (at offset 10)");
e = new FormatException("message", "source", 3);
test(e, "message", "source", 3,
"FormatException: message (at character 4)\nsource\n ^\n");
e = new FormatException("message", "s1\nsource\ns2", 6);
test(e, "message", "s1\nsource\ns2", 6,
"FormatException: message (at line 2, character 4)\nsource\n ^\n");
var longline = "watermelon cantaloupe " * 8 + "watermelon"; // Length > 160.
var longsource = (longline + "\n") * 25;
var line10 = (longline.length + 1) * 9;
e = new FormatException("message", longsource, line10);
test(
e,
"message",
longsource,
line10,
"FormatException: message (at line 10, character 1)\n"
"${longline.substring(0, 75)}...\n^\n");
e = new FormatException("message", longsource, line10 - 1);
test(
e,
"message",
longsource,
line10 - 1,
"FormatException: message (at line 9, "
"character ${longline.length + 1})\n"
"...${longline.substring(longline.length - 75)}\n"
"${' ' * 78}^\n");
var half = longline.length ~/ 2;
e = new FormatException("message", longsource, line10 + half);
test(
e,
"message",
longsource,
line10 + half,
"FormatException: message (at line 10, character ${half + 1})\n"
"...${longline.substring(half - 36, half + 36)}...\n"
"${' ' * 39}^\n");
var sourceNL = "\nsource with leading NL";
e = new FormatException("message", sourceNL, 2);
test(
e,
"message",
sourceNL,
2,
"FormatException: message (at line 2, character 2)\n"
"source with leading NL\n"
" ^\n");
var sourceNL2 = "\n\nsource with leading NL";
e = new FormatException("message", sourceNL2, 2);
test(
e,
"message",
sourceNL2,
2,
"FormatException: message (at line 3, character 1)\n"
"source with leading NL\n"
"^\n");
}

View file

@ -0,0 +1,43 @@
// Copyright (c) 2014, 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.
// SharedOptions=-Da=true -Db=false -Dc=3 -Dd=STRING
import "package:expect/expect.dart";
class Foo {}
const
bool // //# 01: ok
int // //# 02: compile-time error
String // //# 03: compile-time error
Foo // //# 04: compile-time error
a = const bool.fromEnvironment('a');
const
bool // //# 05: ok
int // //# 06: compile-time error
String // //# 07: compile-time error
Foo // //# 08: compile-time error
b = const bool.fromEnvironment('b');
const
bool // //# 09: compile-time error
int // //# 10: ok
String // //# 11: compile-time error
Foo // //# 12: compile-time error
c = const int.fromEnvironment('c');
const
bool // //# 13: compile-time error
int // //# 14: compile-time error
String // //# 15: ok
Foo // //# 16: compile-time error
d = const String.fromEnvironment('d');
main() {
Expect.equals(a, true);
Expect.equals(b, false);
Expect.equals(c, 3);
Expect.equals(d, 'STRING');
}

View file

@ -0,0 +1,42 @@
// Copyright (c) 2014, 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.
import "package:expect/expect.dart";
class Foo {}
const
bool // //# 01: ok
int // //# 02: compile-time error
String //# 03: compile-time error
Foo // //# 04: compile-time error
a = const bool.fromEnvironment('a');
const
bool // //# 05: ok
int // //# 06: compile-time error
String //# 07: compile-time error
Foo // //# 08: compile-time error
b = const bool.fromEnvironment('b');
const
bool // //# 09: compile-time error
int // //# 10: ok
String //# 11: compile-time error
Foo // //# 12: compile-time error
c = const int.fromEnvironment('c');
const
bool // //# 13: compile-time error
int // //# 14: compile-time error
String //# 15: ok
Foo // //# 16: compile-time error
d = const String.fromEnvironment('d');
main() {
Expect.equals(a, false);
Expect.equals(b, false);
Expect.equals(c, null);
Expect.equals(d, null);
}

View file

@ -0,0 +1,164 @@
// Copyright (c) 2011, 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.
// Sanity check on the growing behavior of a growable list.
import "package:expect/expect.dart";
void main() {
testConstructor();
// Concurrent modification checks are only guaranteed in checked mode.
testConcurrentModification();
}
// Iterable generating numbers in range [0..count).
// May perform callback at some point underways.
class TestIterableBase extends Iterable<int> {
final int length;
final int count;
// call [callback] if generating callbackIndex.
final int callbackIndex;
final Function callback;
TestIterableBase(this.length, this.count, this.callbackIndex, this.callback);
Iterator<int> get iterator => new CallbackIterator(this);
}
class TestIterable extends TestIterableBase {
TestIterable(count, [callbackIndex = -1, callback])
: super(-1, count, callbackIndex, callback);
int get length => throw "SHOULD NOT BE CALLED";
}
// Implement Set for private EfficientLengthIterable interface.
class EfficientTestIterable extends TestIterableBase implements Set<int> {
EfficientTestIterable(length, count, [callbackIndex = -1, callback])
: super(length, count, callbackIndex, callback);
// Avoid warnings because we don't actually implement Set.
noSuchMethod(i) => super.noSuchMethod(i);
Set<R> cast<R>() => throw "not used by test";
}
class CallbackIterator implements Iterator<int> {
TestIterableBase _iterable;
int? _current = null;
int _nextIndex = 0;
CallbackIterator(this._iterable);
bool moveNext() {
if (_nextIndex >= _iterable.count) {
_current = null;
return false;
}
_current = _nextIndex;
_nextIndex++;
if (_current == _iterable.callbackIndex) {
_iterable.callback();
}
return true;
}
int get current => _current ?? (throw StateError("No current element"));
}
void testConstructor() {
// Constructor can make both growable and fixed-length lists.
testGrowable(list) {
Expect.isTrue(list is List<int>);
Expect.isFalse(list is List<String>);
int length = list.length;
list.add(42);
Expect.equals(list.length, length + 1);
}
testFixedLength(list) {
Expect.isTrue(list is List<int>);
int length = list.length;
Expect.throws(() {
list.add(42);
});
Expect.equals(length, list.length);
}
testThrowsOrTypeError(fn, [name]) {
Expect.throws(fn, (_) => true, name);
}
testFixedLength(new List<int?>(0));
testFixedLength(new List<int?>(5));
testFixedLength(new List<int?>.filled(5, null)); // default growable: false.
testGrowable(new List<int?>());
testGrowable(new List<int?>()..length = 5);
testGrowable(new List<int?>.filled(5, null, growable: true));
Expect.throwsArgumentError(() => new List<int?>(-1), "-1");
// There must be limits. Fix this test if we ever allow 2^63 elements.
Expect.throws(() => new List<int?>(0x7ffffffffffff000),
(e) => e is OutOfMemoryError || e is ArgumentError, "bignum");
Expect.throwsArgumentError(() => new List<int?>(null), "null");
testThrowsOrTypeError(
() => new List([] as dynamic), // Cast to avoid warning.
'list');
testThrowsOrTypeError(() => new List([42] as dynamic), "list2");
}
void testConcurrentModification() {
// Without EfficientLengthIterable interface
{
// Change length of list after 200 additions.
var l = [];
var ci = new TestIterable(257, 200, () {
l.add("X");
});
Expect.throws(() {
l.addAll(ci);
}, (e) => e is ConcurrentModificationError, "cm1");
}
{
// Change length of list after 200 additions.
var l = [];
var ci = new TestIterable(257, 200, () {
l.length = 0;
});
Expect.throws(() {
l.addAll(ci);
}, (e) => e is ConcurrentModificationError, "cm2");
}
// With EfficientLengthIterable interface (uses length).
{
// Change length of list after 20 additions.
var l = [];
var ci = new EfficientTestIterable(257, 257, 20, () {
l.add("X");
});
Expect.throws(() {
l.addAll(ci);
}, (e) => e is ConcurrentModificationError, "cm3");
}
{
var l = [];
var ci = new EfficientTestIterable(257, 257, 20, () {
l.length = 0;
});
Expect.throws(() {
l.addAll(ci);
}, (e) => e is ConcurrentModificationError, "cm4");
}
{
// Length 500, only 250 elements.
var l = [];
var ci = new EfficientTestIterable(500, 250);
l.addAll(ci);
Expect.listEquals(new List.generate(250, (x) => x), l, "cm5");
}
{
// Length 250, but 500 elements.
var l = [];
var ci = new EfficientTestIterable(250, 500);
l.addAll(ci);
Expect.listEquals(new List.generate(500, (x) => x), l, "cm6");
}
}

View file

@ -0,0 +1,37 @@
// Copyright (c) 2012, 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.
library hasNextIterator.test;
import "package:expect/expect.dart";
import 'dart:collection';
main() {
var it = new HasNextIterator([].iterator);
Expect.isFalse(it.hasNext);
Expect.isFalse(it.hasNext);
Expect.throwsStateError(() => it.next());
Expect.isFalse(it.hasNext);
it = new HasNextIterator([1].iterator);
Expect.isTrue(it.hasNext);
Expect.isTrue(it.hasNext);
Expect.equals(1, it.next());
Expect.isFalse(it.hasNext);
Expect.isFalse(it.hasNext);
Expect.throwsStateError(() => it.next());
Expect.isFalse(it.hasNext);
it = new HasNextIterator([1, 2].iterator);
Expect.isTrue(it.hasNext);
Expect.isTrue(it.hasNext);
Expect.equals(1, it.next());
Expect.isTrue(it.hasNext);
Expect.isTrue(it.hasNext);
Expect.equals(2, it.next());
Expect.isFalse(it.hasNext);
Expect.isFalse(it.hasNext);
Expect.throwsStateError(() => it.next());
Expect.isFalse(it.hasNext);
}

View file

@ -0,0 +1,311 @@
// Copyright (c) 2013, 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.
//
// VMOptions=
// VMOptions=--use_internal_hash_map
// Tests of hash map behavior, with focus in iteration and concurrent
// modification errors.
library hash_map2_test;
import "package:expect/expect.dart";
import 'dart:collection';
testMap(Map newMap(), Map newMapFrom(Map map)) {
Map gen(int from, int to) {
Map map = new LinkedHashMap();
for (int i = from; i < to; i++) map[i] = i;
return map;
}
bool odd(dynamic n) => ((n as int) & 1) == 1;
bool even(dynamic n) => ((n as int) & 1) == 0;
void addAll(Map toMap, Map fromMap) {
fromMap.forEach((k, v) {
toMap[k] = v;
});
}
{
// Test growing to largish capacity.
Map map = newMap();
for (int i = 0; i < 256; i++) {
map[i] = i;
}
addAll(map, gen(256, 512));
addAll(map, newMapFrom(gen(512, 1000)));
Expect.equals(1000, map.length);
// Remove half.
for (int i = 0; i < 1000; i += 2) map.remove(i);
Expect.equals(500, map.length);
Expect.isFalse(map.keys.any(even));
Expect.isTrue(map.keys.every(odd));
// Re-add all.
addAll(map, gen(0, 1000));
Expect.equals(1000, map.length);
}
{
// Test having many deleted elements.
Map map = newMap();
map[0] = 0;
for (int i = 0; i < 1000; i++) {
map[i + 1] = i + 1;
map.remove(i);
Expect.equals(1, map.length);
}
}
{
// Test having many elements with same hashCode
Map map = newMap();
for (int i = 0; i < 1000; i++) {
map[new BadHashCode()] = 0;
}
Expect.equals(1000, map.length);
}
{
// Check concurrent modification
Map map = newMap()
..[0] = 0
..[1] = 1;
{
// Test adding before a moveNext.
Iterator iter = map.keys.iterator;
iter.moveNext();
map[1] = 9; // Updating existing key isn't a modification.
iter.moveNext();
map[2] = 2;
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test adding after last element.
Iterator iter = map.keys.iterator;
Expect.equals(3, map.length);
iter.moveNext();
iter.moveNext();
iter.moveNext();
map[3] = 3;
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test removing during iteration.
Iterator iter = map.keys.iterator;
iter.moveNext();
map.remove(1000); // Not a modification if it's not there.
iter.moveNext();
int n = iter.current;
map.remove(n);
// Removing doesn't change current.
Expect.equals(n, iter.current);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test removing after last element.
Iterator iter = map.keys.iterator;
Expect.equals(3, map.length);
iter.moveNext();
iter.moveNext();
iter.moveNext();
int n = iter.current;
map.remove(n);
// Removing doesn't change current.
Expect.equals(n, iter.current);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test that updating value of existing key doesn't cause concurrent
// modification error.
Iterator iter = map.keys.iterator;
Expect.equals(2, map.length);
iter.moveNext();
int n = iter.current;
map[n] = n * 2;
iter.moveNext();
Expect.equals(map[iter.current], iter.current);
}
{
// Test that modification during putIfAbsent is not an error.
map.putIfAbsent(4, () {
map[5] = 5;
map[4] = -1;
return 4;
});
Expect.equals(4, map[4]);
Expect.equals(5, map[5]);
}
{
// Check adding many existing keys isn't considered modification.
Map map2 = newMap();
for (var key in map.keys) {
map2[key] = map[key] + 1;
}
Iterator iter = map.keys.iterator;
addAll(map, map2);
// Shouldn't throw.
iter.moveNext();
}
}
{
// Regression test for bug in putIfAbsent where adding an element
// that make the table grow, can be lost.
Map map = newMap();
map.putIfAbsent("S", () => 0);
map.putIfAbsent("T", () => 0);
map.putIfAbsent("U", () => 0);
map.putIfAbsent("C", () => 0);
map.putIfAbsent("a", () => 0);
map.putIfAbsent("b", () => 0);
map.putIfAbsent("n", () => 0);
Expect.isTrue(map.containsKey("n"));
}
{
// Check that putIfAbsent works just as well as put.
Map map = newMap();
for (int i = 0; i < 128; i++) {
map.putIfAbsent(i, () => i);
Expect.isTrue(map.containsKey(i));
map.putIfAbsent(i >> 1, () => -1); // Never triggers.
}
for (int i = 0; i < 128; i++) {
Expect.equals(i, map[i]);
}
}
{
// Check that updating existing elements is not a modification.
// This must be the case even if the underlying data structure is
// nearly full.
for (int i = 1; i < 128; i++) {
// Create maps of different sizes, some of which should be
// at a limit of the underlying data structure.
Map map = newMapFrom(gen(0, i));
// ForEach-iteration.
map.forEach((key, v) {
Expect.equals(key, map[key]);
map[key] = key + 1;
map.remove(1000); // Removing something not there.
map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
// Doesn't cause ConcurrentModificationError.
});
// for-in iteration.
for (int key in map.keys) {
Expect.equals(key + 1, map[key]);
map[key] = map[key] + 1;
map.remove(1000); // Removing something not there.
map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
// Doesn't cause ConcurrentModificationError.
}
// Raw iterator.
Iterator iter = map.keys.iterator;
for (int key = 0; key < i; key++) {
Expect.equals(key + 2, map[key]);
map[key] = key + 3;
map.remove(1000); // Removing something not there.
map.putIfAbsent(key, () => Expect.fail("SHOULD NOT BE ABSENT"));
// Doesn't cause ConcurrentModificationError on the moveNext.
}
iter.moveNext(); // Should not throw.
// Remove a lot of elements, which can cause a re-tabulation.
for (int key = 1; key < i; key++) {
Expect.equals(key + 3, map[key]);
map.remove(key);
}
iter = map.keys.iterator;
map[0] = 2;
iter.moveNext(); // Should not throw.
}
}
{
// Check that null can be in the map.
Map map = newMap();
map[null] = 0;
Expect.equals(1, map.length);
Expect.isTrue(map.containsKey(null));
Expect.isNull(map.keys.first);
Expect.isNull(map.keys.last);
map[null] = 1;
Expect.equals(1, map.length);
Expect.isTrue(map.containsKey(null));
map.remove(null);
Expect.isTrue(map.isEmpty);
Expect.isFalse(map.containsKey(null));
// Created using map.from.
map = newMapFrom(new Map()..[null] = 0);
Expect.equals(1, map.length);
Expect.isTrue(map.containsKey(null));
Expect.isNull(map.keys.first);
Expect.isNull(map.keys.last);
map[null] = 1;
Expect.equals(1, map.length);
Expect.isTrue(map.containsKey(null));
map.remove(null);
Expect.isTrue(map.isEmpty);
Expect.isFalse(map.containsKey(null));
Map fromMap = new Map();
fromMap[1] = 0;
fromMap[2] = 0;
fromMap[3] = 0;
fromMap[null] = 0;
fromMap[4] = 0;
fromMap[5] = 0;
fromMap[6] = 0;
Expect.equals(7, fromMap.length);
// map that grows with null in it.
map = newMapFrom(fromMap);
Expect.equals(7, map.length);
for (int i = 7; i < 128; i++) {
map[i] = 0;
}
Expect.equals(128, map.length);
Expect.isTrue(map.containsKey(null));
map[null] = 1;
Expect.equals(128, map.length);
Expect.isTrue(map.containsKey(null));
map.remove(null);
Expect.equals(127, map.length);
Expect.isFalse(map.containsKey(null));
}
}
void main() {
Expect.isTrue(new HashMap<int, String>() is Map<int, String>);
Expect.isTrue(new LinkedHashMap<int, String>() is Map<int, String>);
Expect.isTrue(new HashMap<String, int>.from({}) is Map<String, int>);
Expect.isTrue(new LinkedHashMap<String, int>.from({}) is Map<String, int>);
Expect.isTrue(<String, int>{} is Map<String, int>);
Expect.isTrue(const <String, int>{} is Map<String, int>);
testMap(() => new HashMap(), (m) => new HashMap.from(m));
testMap(() => new LinkedHashMap(), (m) => new LinkedHashMap.from(m));
}
class BadHashCode {
static int idCounter = 0;
final int id;
BadHashCode() : id = idCounter++;
int get hashCode => 42;
}

View file

@ -0,0 +1,23 @@
// Copyright (c) 2011, 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.
import "package:expect/expect.dart";
// Test program for the HashMap class.
class HashMapTest {
static testMain() {
var m = new Map();
Expect.equals(0, m.length);
Expect.equals(true, m.isEmpty);
m["one"] = 1;
Expect.equals(1, m.length);
Expect.equals(false, m.isEmpty);
Expect.equals(1, m["one"]);
}
}
main() {
HashMapTest.testMain();
}

View file

@ -0,0 +1,363 @@
// Copyright (c) 2013, 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.
//
// VMOptions=
// Tests of hash set behavior, with focus in iteration and concurrent
// modification errors.
library hash_map2_test;
import "package:expect/expect.dart";
import 'dart:collection';
import 'dart:math' as math;
testSet(Set newSet(), Set newSetFrom(Iterable from)) {
Set gen(int from, int to) =>
new Set.from(new Iterable.generate(to - from, (n) => n + from));
bool odd(n) => (n & 1) == 1;
bool even(n) => (n & 1) == 0;
{
// Test growing to largish capacity.
Set set = newSet();
for (int i = 0; i < 256; i++) {
set.add(i);
}
set.addAll(gen(256, 512));
set.addAll(newSetFrom(gen(512, 1000)));
Expect.equals(1000, set.length);
// Remove half.
for (int i = 0; i < 1000; i += 2) set.remove(i);
Expect.equals(500, set.length);
Expect.isFalse(set.any(even));
Expect.isTrue(set.every(odd));
// Re-add all.
set.addAll(gen(0, 1000));
Expect.equals(1000, set.length);
}
{
// Test having many deleted elements.
Set set = newSet();
set.add(0);
for (int i = 0; i < 1000; i++) {
set.add(i + 1);
set.remove(i);
Expect.equals(1, set.length);
}
}
{
// Test having many elements with same hashCode
Set set = newSet();
for (int i = 0; i < 1000; i++) {
set.add(new BadHashCode());
}
Expect.equals(1000, set.length);
}
{
// Check concurrent modification
Set set = newSet()..add(0)..add(1);
{
// Test adding before a moveNext.
Iterator iter = set.iterator;
iter.moveNext();
set.add(1); // Updating existing key isn't a modification.
iter.moveNext();
set.add(2);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test adding after last element.
Iterator iter = set.iterator;
Expect.equals(3, set.length);
iter.moveNext();
iter.moveNext();
iter.moveNext();
set.add(3);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test removing during iteration.
Iterator iter = set.iterator;
iter.moveNext();
set.remove(1000); // Not a modification if it's not there.
iter.moveNext();
int n = iter.current;
set.remove(n);
// Removing doesn't change current.
Expect.equals(n, iter.current);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test removing after last element.
Iterator iter = set.iterator;
Expect.equals(3, set.length);
iter.moveNext();
iter.moveNext();
iter.moveNext();
int n = iter.current;
set.remove(n);
// Removing doesn't change current.
Expect.equals(n, iter.current);
Expect.throws(iter.moveNext, (e) => e is Error);
}
{
// Test that updating value doesn't cause error.
Iterator iter = set.iterator;
Expect.equals(2, set.length);
iter.moveNext();
int n = iter.current;
set.add(n);
iter.moveNext();
Expect.isTrue(set.contains(iter.current));
}
{
// Check adding many existing values isn't considered modification.
Set set2 = newSet();
for (var value in set) {
set2.add(value);
}
Iterator iter = set.iterator;
set.addAll(set2);
// Shouldn't throw.
iter.moveNext();
}
}
{
// Check that updating existing elements is not a modification.
// This must be the case even if the underlying data structure is
// nearly full.
for (int i = 1; i < 128; i++) {
// Create maps of different sizes, some of which should be
// at a limit of the underlying data structure.
Set set = newSetFrom(gen(0, i));
Iterator iter = set.iterator;
for (int j = 0; j < i; j++) {
set.add(j);
}
iter.moveNext(); // Should not throw.
for (int j = 1; j < i; j++) {
set.remove(j);
}
iter = set.iterator;
set.add(0);
iter.moveNext(); // Should not throw.
}
}
{
// Check that null can be in the set.
Set set = newSet();
set.add(null);
Expect.equals(1, set.length);
Expect.isTrue(set.contains(null));
Expect.isNull(set.first);
Expect.isNull(set.last);
set.add(null);
Expect.equals(1, set.length);
Expect.isTrue(set.contains(null));
set.remove(null);
Expect.isTrue(set.isEmpty);
Expect.isFalse(set.contains(null));
// Created using Set.from.
set = newSetFrom([null]);
Expect.equals(1, set.length);
Expect.isTrue(set.contains(null));
Expect.isNull(set.first);
Expect.isNull(set.last);
set.add(null);
Expect.equals(1, set.length);
Expect.isTrue(set.contains(null));
set.remove(null);
Expect.isTrue(set.isEmpty);
Expect.isFalse(set.contains(null));
// Set that grows with null in it.
set = newSetFrom([1, 2, 3, null, 4, 5, 6]);
Expect.equals(7, set.length);
for (int i = 7; i < 128; i++) {
set.add(i);
}
Expect.equals(128, set.length);
Expect.isTrue(set.contains(null));
set.add(null);
Expect.equals(128, set.length);
Expect.isTrue(set.contains(null));
set.remove(null);
Expect.equals(127, set.length);
Expect.isFalse(set.contains(null));
}
{
// Check that addAll and clear works.
Set set = newSet();
set.addAll([]);
Expect.isTrue(set.isEmpty);
set.addAll([1, 3, 2]);
Expect.equals(3, set.length);
Expect.isTrue(set.contains(1));
Expect.isTrue(set.contains(3));
Expect.isTrue(set.contains(2));
Expect.isFalse(set.contains(4));
set.clear();
Expect.isTrue(set.isEmpty);
}
{
// Check that removeWhere and retainWhere work.
Set set = newSetFrom([1, 2, 3]);
set.removeWhere((each) => each == 2);
Expect.equals(2, set.length);
Expect.isTrue(set.contains(1));
Expect.isFalse(set.contains(2));
Expect.isTrue(set.contains(3));
set.retainWhere((each) => each == 3);
Expect.equals(1, set.length);
Expect.isFalse(set.contains(1));
Expect.isFalse(set.contains(2));
Expect.isTrue(set.contains(3));
}
{
// Test lookup
Set set = newSet();
var m1a = new Mutable(1);
var m1b = new Mutable(1);
var m2a = new Mutable(2);
var m2b = new Mutable(2);
Expect.isNull(set.lookup(m1a));
Expect.isNull(set.lookup(m1b));
set.add(m1a);
Expect.identical(m1a, set.lookup(m1a));
Expect.identical(m1a, set.lookup(m1b));
Expect.isNull(set.lookup(m2a));
Expect.isNull(set.lookup(m2b));
set.add(m2a);
Expect.identical(m2a, set.lookup(m2a));
Expect.identical(m2a, set.lookup(m2b));
set.add(m2b); // Adding doesn't change element.
Expect.identical(m2a, set.lookup(m2a));
Expect.identical(m2a, set.lookup(m2b));
set.remove(m1a);
set.add(m1b);
Expect.identical(m1b, set.lookup(m1a));
Expect.identical(m1b, set.lookup(m1b));
set.add(1);
Expect.identical(1, set.lookup(1.0));
set.add(-0.0);
Expect.identical(-0.0, set.lookup(0.0));
}
{
// Test special hash codes
Set set = newSet();
List keys = [];
// Powers of two
for (int i = 63; i >= 2; --i) {
keys.add(new Mutable(math.pow(2, i) as int));
}
for (var key in keys) {
Expect.isTrue(set.add(key));
}
for (var key in keys) {
Expect.isTrue(set.contains(key));
}
}
}
void testIdentitySet(Set create()) {
Set set = create();
set.add(1);
set.add(2);
set.add(1); // Integers are identical if equal.
Expect.equals(2, set.length);
var complex = 4;
complex = set.length == 2 ? complex ~/ 4 : 87; // Avoid compile-time constant.
Expect.isTrue(set.contains(complex)); // 1 is in set, even if computed.
set.clear();
// All compile time constants are identical to themselves.
var constants = [
double.infinity,
double.nan, -0.0, //# 01: ok
0.0, 42, "", null, false, true, #bif, testIdentitySet
];
set.addAll(constants);
Expect.equals(constants.length, set.length);
for (var c in constants) {
Expect.isTrue(set.contains(c), "constant: $c");
}
Expect.isTrue(set.containsAll(constants), "constants: $set");
set.clear();
var m1 = new Mutable(1);
var m2 = new Mutable(2);
var m3 = new Mutable(3);
var m4 = new Mutable(2); // Equal to m2, but not identical.
set.addAll([m1, m2, m3, m4]);
Expect.equals(4, set.length);
Expect.equals(3, m3.hashCode);
m3.id = 1;
Expect.equals(1, m3.hashCode);
// Changing hashCode doesn't affect lookup.
Expect.isTrue(set.contains(m3));
Expect.isTrue(set.contains(m1));
set.remove(m3);
Expect.isFalse(set.contains(m3));
Expect.isTrue(set.contains(m1));
Expect.identical(m1, set.lookup(m1));
Expect.identical(null, set.lookup(m3));
}
void main() {
testSet(() => new Set(), (m) => new Set.from(m));
testSet(() => new HashSet(), (m) => new HashSet.from(m));
testSet(() => new LinkedHashSet(), (m) => new LinkedHashSet.from(m));
testIdentitySet(() => new Set.identity());
testIdentitySet(() => new HashSet.identity());
testIdentitySet(() => new LinkedHashSet.identity());
testIdentitySet(() => new HashSet(
equals: (x, y) => identical(x, y), hashCode: (x) => identityHashCode(x)));
testIdentitySet(() => new LinkedHashSet(
equals: (x, y) => identical(x, y), hashCode: (x) => identityHashCode(x)));
}
class BadHashCode {
static int idCounter = 0;
final int id;
BadHashCode() : id = idCounter++;
int get hashCode => 42;
// operator == is identity.
// Can't make a bad compareTo that isn't invalid.
int compareTo(BadHashCode other) => id - other.id;
}
class Mutable {
int id;
Mutable(this.id);
int get hashCode => id;
bool operator ==(other) => other is Mutable && id == other.id;
}

View file

@ -0,0 +1,30 @@
// 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.
// Tests of hash set type checking.
library hash_set_type_check_test;
import "package:expect/expect.dart";
import 'dart:collection';
// TODO: all this test does now is verify that lookup takes a non-T
// should merge this with `hash_test_test`.
testSet(Set<String> newSet()) {
Set<String> s = newSet();
Expect.isNull(s.lookup(1));
}
void main() {
testSet(() => new Set<String>());
testSet(() => new HashSet<String>());
testSet(() => new LinkedHashSet<String>());
testSet(() => new Set<String>.identity());
testSet(() => new HashSet<String>.identity());
testSet(() => new LinkedHashSet<String>.identity());
testSet(() => new HashSet<String>(
equals: (x, y) => identical(x, y), hashCode: (x) => identityHashCode(x)));
testSet(() => new LinkedHashSet<String>(
equals: (x, y) => identical(x, y), hashCode: (x) => identityHashCode(x)));
}

View file

@ -0,0 +1,21 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
double fib(double n) {
return n <= 1.0 ? 1.0 : fib(n - 1) + fib(n - 2);
}
main() {
// Compute the same value in a way that won't be optimized away so the results
// are different objects in memory.
var a = fib(5.0) + 1.0;
var b = fib(4.0) + 4.0;
Expect.isTrue(identical(a, b));
Expect.equals(identityHashCode(a), identityHashCode(b));
Expect.equals(a, b);
Expect.equals(a.hashCode, b.hashCode);
}

View file

@ -0,0 +1,47 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
class Override {
int hash = -1;
int get superHash => super.hashCode;
int get hashCode => hash;
int foo() => hash; // Just some function that can be closurized.
bool operator ==(Object other) => other is Override && other.hash == hash;
}
int bar() => 42; // Some global function.
main() {
var o = new Object();
var hash = o.hashCode;
// Doesn't change.
Expect.equals(hash, o.hashCode);
Expect.equals(hash, identityHashCode(o));
var c = new Override();
int identityHash = c.superHash;
hash = (identityHash == 42) ? 37 : 42;
c.hash = hash;
Expect.equals(hash, c.hashCode);
Expect.equals(identityHash, identityHashCode(c));
// These classes don't override hashCode.
var samples = [0, 0x10000000, 1.5, -0, null, true, false, const Object()];
for (var v in samples) {
print(v);
Expect.equals(v.hashCode, identityHashCode(v));
}
// These do, or might do, but we can still use hashCodeOf and get the same
// result each time.
samples = ["string", "", (x) => 42, c.foo, bar];
for (var v in samples) {
print(v);
Expect.equals(v.hashCode, v.hashCode);
Expect.equals(identityHashCode(v), identityHashCode(v));
}
}

View file

@ -0,0 +1,15 @@
// Copyright (c) 2013, 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.
// Test that the internal hidden library doesn't make problems with taking
// stack-traces.
main() {
print(['x'].where((_) {
// We actually don't really care for the successful case. We just want to
// make sure that the test doesn't crash when it is negative.
throw 'fisk'; // //# 01: runtime error
return true;
}).toList());
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0, 0.ceil());
Expect.equals(1, 1.ceil());
Expect.equals(0x1234, 0x1234.ceil());
Expect.equals(0x12345678, 0x12345678.ceil());
Expect.equals(0x123456789AB, 0x123456789AB.ceil());
Expect.equals(big, big.ceil());
Expect.equals(-1, (-1).ceil());
Expect.equals(-0x1234, (-0x1234).ceil());
Expect.equals(-0x12345678, (-0x12345678).ceil());
Expect.equals(-0x123456789AB, (-0x123456789AB).ceil());
Expect.equals(-big, (-big).ceil());
Expect.isTrue(0.ceil() is int);
Expect.isTrue(1.ceil() is int);
Expect.isTrue(0x1234.ceil() is int);
Expect.isTrue(0x12345678.ceil() is int);
Expect.isTrue(0x123456789AB.ceil() is int);
Expect.isTrue(big.ceil() is int);
Expect.isTrue((-1).ceil() is int);
Expect.isTrue((-0x1234).ceil() is int);
Expect.isTrue((-0x12345678).ceil() is int);
Expect.isTrue((-0x123456789AB).ceil() is int);
Expect.isTrue((-big).ceil() is int);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0.0, 0.ceilToDouble());
Expect.equals(1.0, 1.ceilToDouble());
Expect.equals(0x1234, 0x1234.ceilToDouble());
Expect.equals(0x12345678, 0x12345678.ceilToDouble());
Expect.equals(0x123456789AB, 0x123456789AB.ceilToDouble());
Expect.equals(81985529216486900.0, big.ceilToDouble());
Expect.equals(-1.0, (-1).ceilToDouble());
Expect.equals(-0x1234, (-0x1234).ceilToDouble());
Expect.equals(-0x12345678, (-0x12345678).ceilToDouble());
Expect.equals(-0x123456789AB, (-0x123456789AB).ceilToDouble());
Expect.equals(-81985529216486900.0, (-big).ceilToDouble());
Expect.isTrue(0.ceilToDouble() is double);
Expect.isTrue(1.ceilToDouble() is double);
Expect.isTrue(0x1234.ceilToDouble() is double);
Expect.isTrue(0x12345678.ceilToDouble() is double);
Expect.isTrue(0x123456789AB.ceilToDouble() is double);
Expect.isTrue(big.ceilToDouble() is double);
Expect.isTrue((-1).ceilToDouble() is double);
Expect.isTrue((-0x1234).ceilToDouble() is double);
Expect.isTrue((-0x12345678).ceilToDouble() is double);
Expect.isTrue((-0x123456789AB).ceilToDouble() is double);
Expect.isTrue((-big).ceilToDouble() is double);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0, 0.floor());
Expect.equals(1, 1.floor());
Expect.equals(0x1234, 0x1234.floor());
Expect.equals(0x12345678, 0x12345678.floor());
Expect.equals(0x123456789AB, 0x123456789AB.floor());
Expect.equals(big, big.floor());
Expect.equals(-1, (-1).floor());
Expect.equals(-0x1234, (-0x1234).floor());
Expect.equals(-0x12345678, (-0x12345678).floor());
Expect.equals(-0x123456789AB, (-0x123456789AB).floor());
Expect.equals(-big, (-big).floor());
Expect.isTrue(0.floor() is int);
Expect.isTrue(1.floor() is int);
Expect.isTrue(0x1234.floor() is int);
Expect.isTrue(0x12345678.floor() is int);
Expect.isTrue(0x123456789AB.floor() is int);
Expect.isTrue(big.floor() is int);
Expect.isTrue((-1).floor() is int);
Expect.isTrue((-0x1234).floor() is int);
Expect.isTrue((-0x12345678).floor() is int);
Expect.isTrue((-0x123456789AB).floor() is int);
Expect.isTrue((-big).floor() is int);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0.0, 0.floorToDouble());
Expect.equals(1.0, 1.floorToDouble());
Expect.equals(0x1234, 0x1234.floorToDouble());
Expect.equals(0x12345678, 0x12345678.floorToDouble());
Expect.equals(0x123456789AB, 0x123456789AB.floorToDouble());
Expect.equals(81985529216486900.0, big.floorToDouble());
Expect.equals(-1.0, (-1).floorToDouble());
Expect.equals(-0x1234, (-0x1234).floorToDouble());
Expect.equals(-0x12345678, (-0x12345678).floorToDouble());
Expect.equals(-0x123456789AB, (-0x123456789AB).floorToDouble());
Expect.equals(-81985529216486900.0, (-big).floorToDouble());
Expect.isTrue(0.floorToDouble() is double);
Expect.isTrue(1.floorToDouble() is double);
Expect.isTrue(0x1234.floorToDouble() is double);
Expect.isTrue(0x12345678.floorToDouble() is double);
Expect.isTrue(0x123456789AB.floorToDouble() is double);
Expect.isTrue(big.floorToDouble() is double);
Expect.isTrue((-1).floorToDouble() is double);
Expect.isTrue((-0x1234).floorToDouble() is double);
Expect.isTrue((-0x12345678).floorToDouble() is double);
Expect.isTrue((-0x123456789AB).floorToDouble() is double);
Expect.isTrue((-big).floorToDouble() is double);
}

View file

@ -0,0 +1,14 @@
// Copyright (c) 2013, 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.
// SharedOptions=-Da=x -Db=- -Dc=0xg -Dd=+ -Dd=
import "package:expect/expect.dart";
main() {
Expect.isNull(const int.fromEnvironment('a'));
Expect.isNull(const int.fromEnvironment('b'));
Expect.isNull(const int.fromEnvironment('c'));
Expect.isNull(const int.fromEnvironment('d'));
Expect.isNull(const int.fromEnvironment('e'));
}

View file

@ -0,0 +1,11 @@
// Copyright (c) 2013, 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.
// SharedOptions=-Df=-9223372036854775808 -Dg=9223372036854775807
import "package:expect/expect.dart";
main() {
Expect.equals(-9223372036854775808, const int.fromEnvironment('f'));
Expect.equals(9223372036854775807, const int.fromEnvironment('g'));
}

View file

@ -0,0 +1,19 @@
// Copyright (c) 2013, 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.
// SharedOptions=-Da=1 -Db=-12 -Dc=0x123 -Dd=-0x1234 -De=+0x112296 -Df=-9007199254740991 -Dg=9007199254740991 -Dh=-0x8000000000000000 -Di=0x8000000000000000 -Dj=0xDEADBEEFCAFE0000
import "package:expect/expect.dart";
main() {
Expect.equals(1, const int.fromEnvironment('a'));
Expect.equals(-12, const int.fromEnvironment('b'));
Expect.equals(0x123, const int.fromEnvironment('c'));
Expect.equals(-0x1234, const int.fromEnvironment('d'));
Expect.equals(0x112296, const int.fromEnvironment('e'));
Expect.equals(-9007199254740991, const int.fromEnvironment('f'));
Expect.equals(9007199254740991, const int.fromEnvironment('g'));
Expect.equals(-0x8000000000000000, const int.fromEnvironment('h'));
Expect.equals(0x8000000000000000, const int.fromEnvironment('i'));
Expect.equals(0xDEADBEEFCAFE0000, const int.fromEnvironment('j'));
}

View file

@ -0,0 +1,47 @@
// Copyright (c) 2019, 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.
// Extreme values from int_modulo_arith_test. Test cases that that have
// intermediate values that overflow the precision of 'int'.
import "package:expect/expect.dart";
import "dart:math" show pow;
main() {
test(x, e, m, expectedResult) {
var result = x.modPow(e, m);
Expect.equals(expectedResult, result, "$x.modPow($e, $m)");
}
for (int mBase in [
50000000,
94906266, // Smallest integer with square over 2^53.
100000000,
1000000000,
3037000500, // Smallest integer with square over 2^63.
4000000000,
0x7FFFFFFFFFFFF000 + 0xFFC
]) {
// On 'web' platforms skip values outside web number safe range.
if (mBase == mBase + 1) continue;
for (int mAdjustment in [0, 1, 2, 3, -1]) {
int m = mBase + mAdjustment;
for (int e = 1; e < 100; e++) {
// Test "M-k ^ N mod M == (-k) ^ N mod M" for some small values of k.
test(m - 1, e, m, pow(-1, e) % m);
if (e < 53) {
test(m - 2, e, m, pow(-2, e) % m);
}
if (e < 33) {
test(m - 3, e, m, pow(-3, e) % m);
}
if (e < 26) {
test(m - 4, e, m, pow(-4, e) % m);
}
}
}
}
}

View file

@ -0,0 +1,172 @@
// 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.
import "package:expect/expect.dart";
import "dart:math" show pow;
var smallNumber = 1234567890; // is 31-bit integer.
var mediumNumber = 1234567890123456; // is 53-bit integer
testModPow() {
test(x, e, m, expectedResult) {
// Check that expected result is correct, using an unoptimized version.
assert(() {
if (1 is double) return true; // Don't have bignums.
slowModPow(x, e, m) {
var r = 1;
while (e > 0) {
if (e.isOdd) r = (r * x) % m as int;
e >>= 1;
x = (x * x) % m;
}
return r;
}
return slowModPow(x, e, m) == expectedResult;
}());
var result = x.modPow(e, m);
Expect.equals(expectedResult, result, "$x.modPow($e, $m)");
}
test(10, 20, 1, 0);
test(1234567890, 1000000001, 19, 11);
test(1234567890, 19, 1000000001, 122998977);
test(19, 1234567890, 1000000001, 619059596);
test(19, 1000000001, 1234567890, 84910879);
test(1000000001, 19, 1234567890, 872984351);
test(1000000001, 1234567890, 19, 0);
}
testModInverse() {
test(x, m, expectedResult) {
//print("$x op $m == $expectedResult");
// Check that expectedResult is an inverse.
assert(expectedResult < m);
// The 1 % m handles the m = 1 special case.
// This test may overflow if we don't have bignums, so only run on VM.
assert(1 is double || (((x % m) * expectedResult) - 1) % m == 0);
var result = x.modInverse(m);
Expect.equals(expectedResult, result, "$x modinv $m");
if (x > m) {
x = x % m;
var result = x.modInverse(m);
Expect.equals(expectedResult, result, "$x modinv $m");
}
}
testThrows(x, m) {
// Throws if not co-prime, which is a symmetric property.
Expect.throws(() => x.modInverse(m));
Expect.throws(() => m.modInverse(x));
}
test(1, 1, 0);
testThrows(0, 1000000001);
testThrows(2, 4);
testThrows(99, 9);
testThrows(19, 1000000001);
// Co-prime numbers
test(1234567890, 19, 11);
test(1234567890, 1000000001, 189108911);
test(19, 1234567890, 519818059);
test(1000000001, 1234567890, 1001100101);
test(12345, 12346, 12345);
test(12345, 12346, 12345);
test(smallNumber, 137, 42);
test(137, smallNumber, 856087223);
test(mediumNumber, 137, 77);
test(137, mediumNumber, 540686667207353);
}
testGcd() {
// Call testFunc with all combinations and orders of plus/minus
// value and other.
callCombos(value, other, testFunc) {
testFunc(value, other);
testFunc(value, -other);
testFunc(-value, other);
testFunc(-value, -other);
if (value == other) return;
testFunc(other, value);
testFunc(other, -value);
testFunc(-other, value);
testFunc(-other, -value);
}
// Test that gcd of value and other (non-negative) is expectedResult.
// Tests all combinations of positive and negative values and order of
// operands, so use positive values and order is not important.
test(value, other, expectedResult) {
// Check for bug in test.
assert(expectedResult == 0 || value % expectedResult == 0);
assert(expectedResult == 0 || other % expectedResult == 0);
callCombos(value, other, (a, b) {
var result = a.gcd(b);
/// Check that the result is a divisor.
Expect.equals(0, result == 0 ? a : a % result, "$result | $a");
Expect.equals(0, result == 0 ? b : b % result, "$result | $b");
// Check for bug in test. If assert fails, the expected value is too low,
// and the gcd call has found a greater common divisor.
assert(result >= expectedResult);
Expect.equals(expectedResult, result, "$a.gcd($b)");
});
}
// Test that gcd of value and other (non-negative) throws.
testThrows(value, other) {
callCombos(value, other, (a, b) {
Expect.throws(() => a.gcd(b));
});
}
testThrows(2.5, 5); // Not a method on double.
testThrows(5, 2.5); // Not accepting non-int arguments.
// Format:
// test(value1, value2, expectedResult);
test(1, 1, 1); // both are 1
test(1, 2, 1); // one is 1
test(3, 5, 1); // coprime.
test(37, 37, 37); // Same larger prime.
test(9999, 7272, 909); // Larger numbers
test(0, 1000, 1000); // One operand is zero.
test(0, 0, 0); // Both operands are zero.
// Multiplying both operands by a number multiplies result by same number.
test(693, 609, 21);
test(693 << 5, 609 << 5, 21 << 5);
test(693 * 937, 609 * 937, 21 * 937);
test(693 * pow(2, 32), 609 * pow(2, 32), 21 * pow(2, 32));
test(693 * pow(2, 52), 609 * pow(2, 52), 21 * pow(2, 52));
test(693 * pow(2, 53), 609 * pow(2, 53), 21 * pow(2, 53)); // Regression.
test(693 * pow(2, 99), 609 * pow(2, 99), 21 * pow(2, 99));
test(1234567890, 19, 1);
test(1234567890, 1000000001, 1);
test(19, 1000000001, 19);
test(0x3FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF);
test(0x3FFFFFFF, 0x40000000, 1);
test(pow(2, 54), pow(2, 53), pow(2, 53));
test((pow(2, 52) - 1) * pow(2, 10), (pow(2, 26) - 1) * pow(2, 22),
(pow(2, 26) - 1) * pow(2, 10));
}
main() {
testModPow(); // //# modPow: ok
testModInverse();
testGcd();
}

View file

@ -0,0 +1,12 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
void main() {
// These are compile time errors for Dart 2.0.
Expect.throws(() => int.parse("9", radix: 8, /*@compile-error=unspecified*/ onError: "not a function"));
Expect.throws(() => int.parse("9", radix: 8, /*@compile-error=unspecified*/ onError: () => 42));
Expect.throws(() => int.parse("9", radix: 8, /*@compile-error=unspecified*/ onError: (v1, v2) => 42));
}

View file

@ -0,0 +1,68 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
import "dart:math" show pow, log;
void main() {
const String oneByteWhiteSpace = "\x09\x0a\x0b\x0c\x0d\x20"
"\x85" //# 01: ok
"\xa0";
const String whiteSpace = "$oneByteWhiteSpace\u1680"
"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
"\u2028\u2029\u202f\u205f\u3000\ufeff";
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
var zeros = "0" * 64;
void testParse(int result, String radixString, int radix) {
var m = "$radixString/$radix->$result";
Expect.equals(
result, int.parse(radixString.toLowerCase(), radix: radix), m);
Expect.equals(
result, int.parse(radixString.toUpperCase(), radix: radix), m);
Expect.equals(result, int.parse(" $radixString", radix: radix), m);
Expect.equals(result, int.parse("$radixString ", radix: radix), m);
Expect.equals(result, int.parse(" $radixString ", radix: radix), m);
Expect.equals(result, int.parse("+$radixString", radix: radix), m);
Expect.equals(result, int.parse(" +$radixString", radix: radix), m);
Expect.equals(result, int.parse("+$radixString ", radix: radix), m);
Expect.equals(result, int.parse(" +$radixString ", radix: radix), m);
Expect.equals(-result, int.parse("-$radixString", radix: radix), m);
Expect.equals(-result, int.parse(" -$radixString", radix: radix), m);
Expect.equals(-result, int.parse("-$radixString ", radix: radix), m);
Expect.equals(-result, int.parse(" -$radixString ", radix: radix), m);
Expect.equals(
result,
int.parse("$oneByteWhiteSpace$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(
-result,
int.parse("$oneByteWhiteSpace-$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(result,
int.parse("$whiteSpace$radixString$whiteSpace", radix: radix), m);
Expect.equals(-result,
int.parse("$whiteSpace-$radixString$whiteSpace", radix: radix), m);
Expect.equals(result, int.parse("$zeros$radixString", radix: radix), m);
Expect.equals(result, int.parse("+$zeros$radixString", radix: radix), m);
Expect.equals(-result, int.parse("-$zeros$radixString", radix: radix), m);
}
final max = 9223372036854775807;
for (int i = 2; i <= 36; i++) { // //# 02: ok
// Test with bignums. // //# 02: continued
final n = (log(max) / log(i)).truncate(); // //# 02: continued
var digit = digits[i - 1]; // //# 02: continued
testParse((pow(i, n) as int) - 1, digit * n, i); // //# 02: continued
testParse(0, zeros, i); // //# 02: continued
} // //# 02: continued
// Big number.
Expect.equals(9223372036854775807, int.parse("9223372036854775807"));
Expect.equals(-9223372036854775808, int.parse("-9223372036854775808"));
}

View file

@ -0,0 +1,140 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
import "dart:math" show pow, log;
void main() {
const String oneByteWhiteSpace = "\x09\x0a\x0b\x0c\x0d\x20"
"\x85" //# 01: ok
"\xa0";
const String whiteSpace = "$oneByteWhiteSpace\u1680"
"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
"\u2028\u2029\u202f\u205f\u3000\ufeff";
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
var zeros = "0" * 64;
for (int i = 0; i < whiteSpace.length; i++) {
var ws = whiteSpace[i];
Expect.equals(0, int.parse("${ws}0${ws}", radix: 2));
}
void testParse(int result, String radixString, int radix) {
var m = "$radixString/$radix->$result";
Expect.equals(
result, int.parse(radixString.toLowerCase(), radix: radix), m);
Expect.equals(
result, int.parse(radixString.toUpperCase(), radix: radix), m);
Expect.equals(result, int.parse(" $radixString", radix: radix), m);
Expect.equals(result, int.parse("$radixString ", radix: radix), m);
Expect.equals(result, int.parse(" $radixString ", radix: radix), m);
Expect.equals(result, int.parse("+$radixString", radix: radix), m);
Expect.equals(result, int.parse(" +$radixString", radix: radix), m);
Expect.equals(result, int.parse("+$radixString ", radix: radix), m);
Expect.equals(result, int.parse(" +$radixString ", radix: radix), m);
Expect.equals(-result, int.parse("-$radixString", radix: radix), m);
Expect.equals(-result, int.parse(" -$radixString", radix: radix), m);
Expect.equals(-result, int.parse("-$radixString ", radix: radix), m);
Expect.equals(-result, int.parse(" -$radixString ", radix: radix), m);
Expect.equals(
result,
int.parse("$oneByteWhiteSpace$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(
-result,
int.parse("$oneByteWhiteSpace-$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(result,
int.parse("$whiteSpace$radixString$whiteSpace", radix: radix), m);
Expect.equals(-result,
int.parse("$whiteSpace-$radixString$whiteSpace", radix: radix), m);
Expect.equals(result, int.parse("$zeros$radixString", radix: radix), m);
Expect.equals(result, int.parse("+$zeros$radixString", radix: radix), m);
Expect.equals(-result, int.parse("-$zeros$radixString", radix: radix), m);
}
for (int r = 2; r <= 36; r++) {
for (int i = 0; i <= r * r; i++) {
String radixString = i.toRadixString(r);
testParse(i, radixString, r);
}
}
final max = 0x1FFFFFFFFFFFFF;
for (int i = 2; i <= 36; i++) { // //# 02: ok
// Test with bignums. // //# 02: continued
final n = (log(max) / log(i)).truncate(); // //# 02: continued
var digit = digits[i - 1]; // //# 02: continued
testParse((pow(i, n) as int) - 1, digit * n, i); // //# 02: continued
testParse(0, zeros, i); // //# 02: continued
} // //# 02: continued
// Allow both upper- and lower-case letters.
Expect.equals(0xABCD, int.parse("ABCD", radix: 16));
Expect.equals(0xABCD, int.parse("abcd", radix: 16));
Expect.equals(15628859, int.parse("09azAZ", radix: 36));
// Big-ish number. (2^53)
Expect.equals(9007199254740991, int.parse("9007199254740991"));
Expect.equals(-9007199254740991, int.parse("-9007199254740991"));
Expect.equals(-9223372036854775808, int.parse("-9223372036854775808"));
// Allow whitespace before and after the number.
Expect.equals(1, int.parse(" 1", radix: 2));
Expect.equals(1, int.parse("1 ", radix: 2));
Expect.equals(1, int.parse(" 1 ", radix: 2));
Expect.equals(1, int.parse("\n1", radix: 2));
Expect.equals(1, int.parse("1\n", radix: 2));
Expect.equals(1, int.parse("\n1\n", radix: 2));
Expect.equals(1, int.parse("+1", radix: 2));
void testFails(String source, int radix) {
Expect.throws(() {
throw int.parse(source, radix: radix, onError: (s) {
throw "FAIL";
});
}, isFail, "$source/$radix");
Expect.equals(-999, int.parse(source, radix: radix, onError: (s) => -999));
}
for (int i = 2; i < 36; i++) {
var char = i.toRadixString(36);
testFails(char.toLowerCase(), i);
testFails(char.toUpperCase(), i);
}
testFails("", 2);
testFails("+ 1", 2); // No space between sign and digits.
testFails("- 1", 2); // No space between sign and digits.
for (int i = 2; i <= 33; i++) {
// No 0x specially allowed.
// At radix 34 and above, "x" is a valid digit.
testFails("0x10", i);
}
testBadTypes(var source, var radix) {
Expect.throwsTypeError(() => int.parse(source, radix: radix, onError: (s) => 0)); //# badTypes: ok
}
testBadTypes(9, 10);
testBadTypes(true, 10);
testBadTypes("0", true);
testBadTypes("0", "10");
testBadArguments(String source, int radix) {
// If the types match, it should be an ArgumentError of some sort.
Expect.throwsArgumentError(
() => int.parse(source, radix: radix, onError: (s) => 0));
}
testBadArguments("0", -1);
testBadArguments("0", 0);
testBadArguments("0", 1);
testBadArguments("0", 37);
// See also int_parse_radix_bad_handler_test.dart
}
bool isFail(e) => e == "FAIL";

View file

@ -0,0 +1,75 @@
// Copyright (c) 2017, 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.
// Test for int.parse with limited 64-bit integers.
import "package:expect/expect.dart";
main() {
const int ERROR = 42;
int returnError(String s) => ERROR;
Expect.equals(0, int.parse("0"));
Expect.equals(1, int.parse("1"));
Expect.equals(-1, int.parse("-1"));
Expect.equals(0x7ffffffffffffffe, int.parse("0x7ffffffffffffffe"));
Expect.equals(0x7fffffffffffffff, int.parse("0x7fffffffffffffff"));
Expect.equals(-0x7fffffffffffffff, int.parse("-0x7fffffffffffffff"));
Expect.equals(-0x7fffffffffffffff - 1, int.parse("-0x8000000000000000"));
Expect.equals(1 << 63, int.parse("0x8000000000000000"));
Expect.equals(8999999999999999999, int.parse("8999999999999999999"));
Expect.equals(-8999999999999999999, int.parse("-8999999999999999999"));
Expect.equals(9223372036854775807, int.parse("9223372036854775807"));
Expect.equals(-9223372036854775807, int.parse("-9223372036854775807"));
Expect.equals(-9223372036854775807 - 1, int.parse("-9223372036854775808"));
Expect.equals(ERROR, int.parse("-0x8000000000000001", onError: returnError));
Expect.equals(ERROR, int.parse("9223372036854775808", onError: returnError));
Expect.equals(ERROR, int.parse("9223372036854775809", onError: returnError));
Expect.equals(ERROR, int.parse("-9223372036854775809", onError: returnError));
Expect.equals(ERROR, int.parse("10000000000000000000", onError: returnError));
Expect.equals(
0x7fffffffffffffff,
int.parse(
"111111111111111111111111111111111111111111111111111111111111111",
radix: 2));
Expect.equals(
-0x7fffffffffffffff,
int.parse(
"-111111111111111111111111111111111111111111111111111111111111111",
radix: 2));
Expect.equals(
-0x7fffffffffffffff - 1,
int.parse(
"-1000000000000000000000000000000000000000000000000000000000000000",
radix: 2));
Expect.equals(
ERROR,
int.parse(
"1000000000000000000000000000000000000000000000000000000000000000",
radix: 2,
onError: returnError));
Expect.equals(
ERROR,
int.parse(
"1111111111111111111111111111111111111111111111111111111111111110",
radix: 2,
onError: returnError));
Expect.equals(
ERROR,
int.parse(
"1111111111111111111111111111111111111111111111111111111111111111",
radix: 2,
onError: returnError));
Expect.equals(
ERROR,
int.parse(
"-1000000000000000000000000000000000000000000000000000000000000001",
radix: 2,
onError: returnError));
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // truncating arithmetic on web.
Expect.equals(0, 0.round());
Expect.equals(1, 1.round());
Expect.equals(0x1234, 0x1234.round());
Expect.equals(0x12345678, 0x12345678.round());
Expect.equals(0x123456789AB, 0x123456789AB.round());
Expect.equals(big, big.round());
Expect.equals(-1, (-1).round());
Expect.equals(-0x1234, (-0x1234).round());
Expect.equals(-0x12345678, (-0x12345678).round());
Expect.equals(-0x123456789AB, (-0x123456789AB).round());
Expect.equals(-big, (-big).round());
Expect.isTrue(0.round() is int);
Expect.isTrue(1.round() is int);
Expect.isTrue(0x1234.round() is int);
Expect.isTrue(0x12345678.round() is int);
Expect.isTrue(0x123456789AB.round() is int);
Expect.isTrue(big.round() is int);
Expect.isTrue((-1).round() is int);
Expect.isTrue((-0x1234).round() is int);
Expect.isTrue((-0x12345678).round() is int);
Expect.isTrue((-0x123456789AB).round() is int);
Expect.isTrue((-big).round() is int);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0.0, 0.roundToDouble());
Expect.equals(1.0, 1.roundToDouble());
Expect.equals(0x1234, 0x1234.roundToDouble());
Expect.equals(0x12345678, 0x12345678.roundToDouble());
Expect.equals(0x123456789AB, 0x123456789AB.roundToDouble());
Expect.equals(81985529216486900.0, big.roundToDouble());
Expect.equals(-1.0, (-1).roundToDouble());
Expect.equals(-0x1234, (-0x1234).roundToDouble());
Expect.equals(-0x12345678, (-0x12345678).roundToDouble());
Expect.equals(-0x123456789AB, (-0x123456789AB).roundToDouble());
Expect.equals(-81985529216486900.0, (-big).roundToDouble());
Expect.isTrue(0.roundToDouble() is double);
Expect.isTrue(1.roundToDouble() is double);
Expect.isTrue(0x1234.roundToDouble() is double);
Expect.isTrue(0x12345678.roundToDouble() is double);
Expect.isTrue(0x123456789AB.roundToDouble() is double);
Expect.isTrue(big.roundToDouble() is double);
Expect.isTrue((-1).roundToDouble() is double);
Expect.isTrue((-0x1234).roundToDouble() is double);
Expect.isTrue((-0x12345678).roundToDouble() is double);
Expect.isTrue((-0x123456789AB).roundToDouble() is double);
Expect.isTrue((-big).roundToDouble() is double);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0, 0.toInt());
Expect.equals(1, 1.toInt());
Expect.equals(0x1234, 0x1234.toInt());
Expect.equals(0x12345678, 0x12345678.toInt());
Expect.equals(0x123456789AB, 0x123456789AB.toInt());
Expect.equals(big, big.toInt());
Expect.equals(-1, (-1).toInt());
Expect.equals(-0x1234, (-0x1234).toInt());
Expect.equals(-0x12345678, (-0x12345678).toInt());
Expect.equals(-0x123456789AB, (-0x123456789AB).toInt());
Expect.equals(-big, (-big).toInt());
Expect.isTrue(0.toInt() is int);
Expect.isTrue(1.toInt() is int);
Expect.isTrue(0x1234.toInt() is int);
Expect.isTrue(0x12345678.toInt() is int);
Expect.isTrue(0x123456789AB.toInt() is int);
Expect.isTrue(big.toInt() is int);
Expect.isTrue((-1).toInt() is int);
Expect.isTrue((-0x1234).toInt() is int);
Expect.isTrue((-0x12345678).toInt() is int);
Expect.isTrue((-0x123456789AB).toInt() is int);
Expect.isTrue((-big).toInt() is int);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0, 0.truncate());
Expect.equals(1, 1.truncate());
Expect.equals(0x1234, 0x1234.truncate());
Expect.equals(0x12345678, 0x12345678.truncate());
Expect.equals(0x123456789AB, 0x123456789AB.truncate());
Expect.equals(big, big.truncate());
Expect.equals(-1, (-1).truncate());
Expect.equals(-0x1234, (-0x1234).truncate());
Expect.equals(-0x12345678, (-0x12345678).truncate());
Expect.equals(-0x123456789AB, (-0x123456789AB).truncate());
Expect.equals(-big, (-big).truncate());
Expect.isTrue(0.truncate() is int);
Expect.isTrue(1.truncate() is int);
Expect.isTrue(0x1234.truncate() is int);
Expect.isTrue(0x12345678.truncate() is int);
Expect.isTrue(0x123456789AB.truncate() is int);
Expect.isTrue(big.truncate() is int);
Expect.isTrue((-1).truncate() is int);
Expect.isTrue((-0x1234).truncate() is int);
Expect.isTrue((-0x12345678).truncate() is int);
Expect.isTrue((-0x123456789AB).truncate() is int);
Expect.isTrue((-big).truncate() is int);
}

View file

@ -0,0 +1,33 @@
// Copyright (c) 2013, 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.
import 'package:expect/expect.dart';
main() {
const int big = 0x123456789AB0000 + 0xCDEF; // Slightly rounded on web.
Expect.equals(0.0, 0.truncateToDouble());
Expect.equals(1.0, 1.truncateToDouble());
Expect.equals(0x1234, 0x1234.truncateToDouble());
Expect.equals(0x12345678, 0x12345678.truncateToDouble());
Expect.equals(0x123456789AB, 0x123456789AB.truncateToDouble());
Expect.equals(81985529216486900.0, big.truncateToDouble());
Expect.equals(-1.0, (-1).truncateToDouble());
Expect.equals(-0x1234, (-0x1234).truncateToDouble());
Expect.equals(-0x12345678, (-0x12345678).truncateToDouble());
Expect.equals(-0x123456789AB, (-0x123456789AB).truncateToDouble());
Expect.equals(-81985529216486900.0, (-big).truncateToDouble());
Expect.isTrue(0.truncateToDouble() is double);
Expect.isTrue(1.truncateToDouble() is double);
Expect.isTrue(0x1234.truncateToDouble() is double);
Expect.isTrue(0x12345678.truncateToDouble() is double);
Expect.isTrue(0x123456789AB.truncateToDouble() is double);
Expect.isTrue(big.truncateToDouble() is double);
Expect.isTrue((-1).truncateToDouble() is double);
Expect.isTrue((-0x1234).truncateToDouble() is double);
Expect.isTrue((-0x12345678).truncateToDouble() is double);
Expect.isTrue((-0x123456789AB).truncateToDouble() is double);
Expect.isTrue((-big).truncateToDouble() is double);
}

View file

@ -0,0 +1,12 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
import "dart:math" show pow, log;
void main() {
// Big numbers (representable as both Int64 and double).
Expect.equals(9223372036854774784, int.tryParse("9223372036854774784"));
Expect.equals(-9223372036854775808, int.tryParse("-9223372036854775808"));
}

View file

@ -0,0 +1,146 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
import "dart:math" show pow, log;
void main() {
const String oneByteWhiteSpace = "\x09\x0a\x0b\x0c\x0d\x20\xa0";
const String whiteSpace = "$oneByteWhiteSpace\u1680"
"\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a"
"\u2028\u2029\u202f\u205f\u3000\ufeff";
var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
var zeros = "0" * 64;
for (int i = 0; i < whiteSpace.length; i++) {
var ws = whiteSpace[i];
Expect.equals(0, int.parse("${ws}0${ws}", radix: 2));
}
void testParse(int result, String radixString, int radix) {
var m = "$radixString/$radix->$result";
Expect.equals(
result, int.tryParse(radixString.toLowerCase(), radix: radix), m);
Expect.equals(
result, int.tryParse(radixString.toUpperCase(), radix: radix), m);
Expect.equals(result, int.tryParse(" $radixString", radix: radix), m);
Expect.equals(result, int.tryParse("$radixString ", radix: radix), m);
Expect.equals(result, int.tryParse(" $radixString ", radix: radix), m);
Expect.equals(result, int.tryParse("+$radixString", radix: radix), m);
Expect.equals(result, int.tryParse(" +$radixString", radix: radix), m);
Expect.equals(result, int.tryParse("+$radixString ", radix: radix), m);
Expect.equals(result, int.tryParse(" +$radixString ", radix: radix), m);
Expect.equals(-result, int.tryParse("-$radixString", radix: radix), m);
Expect.equals(-result, int.tryParse(" -$radixString", radix: radix), m);
Expect.equals(-result, int.tryParse("-$radixString ", radix: radix), m);
Expect.equals(-result, int.tryParse(" -$radixString ", radix: radix), m);
Expect.equals(
result,
int.tryParse("$oneByteWhiteSpace$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(
-result,
int.tryParse("$oneByteWhiteSpace-$radixString$oneByteWhiteSpace",
radix: radix),
m);
Expect.equals(result,
int.tryParse("$whiteSpace$radixString$whiteSpace", radix: radix), m);
Expect.equals(-result,
int.tryParse("$whiteSpace-$radixString$whiteSpace", radix: radix), m);
Expect.equals(result, int.tryParse("$zeros$radixString", radix: radix), m);
Expect.equals(result, int.tryParse("+$zeros$radixString", radix: radix), m);
Expect.equals(
-result, int.tryParse("-$zeros$radixString", radix: radix), m);
}
for (int r = 2; r <= 36; r++) {
for (int i = 0; i <= r * r; i++) {
String radixString = i.toRadixString(r);
testParse(i, radixString, r);
}
for (var v in [
0,
0x10000,
0x7FFFFFFF,
0x80000000,
0xFFFFFFFF,
0x100000000,
0x7FFFFFFFFFFFF8,
]) {
var string = v.toRadixString(r);
Expect.equals(v, int.tryParse(string, radix: r));
if (v > 0) {
Expect.equals(-v, int.tryParse("-$string", radix: r));
if (r == 16) {
Expect.equals(v, int.tryParse("0x$string"));
Expect.equals(v, int.tryParse("0X$string"));
}
}
}
}
// Allow both upper- and lower-case letters.
Expect.equals(0xABCD, int.tryParse("ABCD", radix: 16));
Expect.equals(0xABCD, int.tryParse("abcd", radix: 16));
Expect.equals(15628859, int.tryParse("09azAZ", radix: 36));
// Bigish numbers (representable precisely as both Int64 and double (2^53)).
Expect.equals(9007199254740991, int.tryParse("9007199254740991"));
Expect.equals(-9007199254740991, int.tryParse("-9007199254740991"));
// Allow whitespace before and after the number.
Expect.equals(1, int.tryParse(" 1", radix: 2));
Expect.equals(1, int.tryParse("1 ", radix: 2));
Expect.equals(1, int.tryParse(" 1 ", radix: 2));
Expect.equals(1, int.tryParse("\n1", radix: 2));
Expect.equals(1, int.tryParse("1\n", radix: 2));
Expect.equals(1, int.tryParse("\n1\n", radix: 2));
Expect.equals(1, int.tryParse("+1", radix: 2));
void testFails(String source, int radix, [String? message]) {
Expect.isNull(int.tryParse(source, radix: radix), message ?? "");
}
for (int i = 2; i < 36; i++) {
var char = i.toRadixString(36);
testFails(char.toLowerCase(), i);
testFails(char.toUpperCase(), i);
}
testFails("", 2);
testFails("+ 1", 2); // No space between sign and digits.
testFails("- 1", 2); // No space between sign and digits.
for (int i = 2; i <= 33; i++) {
// No 0x specially allowed.
// At radix 34 and above, "x" is a valid digit.
testFails("0x10", i);
}
int digitX = 33;
Expect.equals(((digitX * 34) + 1) * 34, int.tryParse("0x10", radix: 34));
Expect.equals(((digitX * 35) + 1) * 35, int.tryParse("0x10", radix: 35));
// Radix must be in the range 2 .. 36.
Expect.throwsArgumentError(() => int.tryParse("0", radix: -1));
Expect.throwsArgumentError(() => int.tryParse("0", radix: 0));
Expect.throwsArgumentError(() => int.tryParse("0", radix: -1));
Expect.throwsArgumentError(() => int.tryParse("0", radix: 37));
// Regression test for http://dartbug.com/32858
Expect.equals(
-0x8000000000000000, int.tryParse("-0x8000000000000000"), "-minint");
// Tests run only with 64-bit integers.
if (0x8000000000000000 < 0) {
// `int` is 64-bit signed integers.
Expect.equals(
-0x8000000000000000, int.tryParse("0x8000000000000000"), "0xUnsigned");
Expect.equals(-1, int.tryParse("0xFFFFFFFFFFFFFFFF"), "0xUnsigned2");
Expect.equals(
0x8000000000000000 - 1, int.tryParse("0x7FFFFFFFFFFFFFFF"), "maxint");
testFails("8000000000000000", 16, "2^63 radix: 16");
testFails("FFFFFFFFFFFFFFFF", 16, "maxuint64 radix: 16");
}
}

View file

@ -0,0 +1,139 @@
// Copyright (c) 2011, 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.
// Testing integers with and without intrinsics.
// VMOptions=
// VMOptions=--no_intrinsify
// VMOptions=--optimization_counter_threshold=10 --no-background_compilation
library integer_arithmetic_test;
import "package:expect/expect.dart";
foo() => 1234567890123456789;
testSmiOverflow() {
var a = 1073741823;
var b = 1073741822;
Expect.equals(2147483645, a + b);
a = -1000000000;
b = 1000000001;
Expect.equals(-2000000001, a - b);
Expect.equals(-1000000001000000000, a * b);
}
testModPow() {
var x, e, m;
x = 1234567890;
e = 1000000001;
m = 19;
Expect.equals(11, x.modPow(e, m));
x = 1234567890;
e = 19;
m = 1000000001;
Expect.equals(122998977, x.modPow(e, m));
x = 19;
e = 1234567890;
m = 1000000001;
Expect.equals(619059596, x.modPow(e, m));
x = 19;
e = 1000000001;
m = 1234567890;
Expect.equals(84910879, x.modPow(e, m));
x = 1000000001;
e = 19;
m = 1234567890;
Expect.equals(872984351, x.modPow(e, m));
x = 1000000001;
e = 1234567890;
m = 19;
Expect.equals(0, x.modPow(e, m));
}
testModInverse() {
var x, m;
x = 1;
m = 1;
Expect.equals(0, x.modInverse(m));
x = 0;
m = 1000000001;
Expect.throws(() => x.modInverse(m), (e) => e is Exception); // Not coprime.
x = 1234567890;
m = 19;
Expect.equals(11, x.modInverse(m));
x = 1234567890;
m = 1000000001;
Expect.equals(189108911, x.modInverse(m));
x = 19;
m = 1000000001;
Expect.throws(() => x.modInverse(m), (e) => e is Exception); // Not coprime.
x = 19;
m = 1234567890;
Expect.equals(519818059, x.modInverse(m));
x = 1000000001;
m = 1234567890;
Expect.equals(1001100101, x.modInverse(m));
x = 1000000001;
m = 19;
Expect.throws(() => x.modInverse(m), (e) => e is Exception); // Not coprime.
}
testGcd() {
var x, m;
x = 1;
m = 1;
Expect.equals(1, x.gcd(m));
x = 693;
m = 609;
Expect.equals(21, x.gcd(m));
x = 693 << 40;
m = 609 << 40;
Expect.equals(21 << 40, x.gcd(m));
x = 609 << 40;
m = 693 << 40;
Expect.equals(21 << 40, x.gcd(m));
x = 0;
m = 1000000001;
Expect.equals(m, x.gcd(m));
x = 1000000001;
m = 0;
Expect.equals(x, x.gcd(m));
x = 0;
m = -1000000001;
Expect.equals(-m, x.gcd(m));
x = -1000000001;
m = 0;
Expect.equals(-x, x.gcd(m));
x = 0;
m = 0;
Expect.equals(0, x.gcd(m));
x = 1234567890;
m = 19;
Expect.equals(1, x.gcd(m));
x = 1234567890;
m = 1000000001;
Expect.equals(1, x.gcd(m));
x = 19;
m = 1000000001;
Expect.equals(19, x.gcd(m));
x = 19;
m = 1234567890;
Expect.equals(1, x.gcd(m));
x = 1000000001;
m = 1234567890;
Expect.equals(1, x.gcd(m));
x = 1000000001;
m = 19;
Expect.equals(19, x.gcd(m));
}
main() {
for (int i = 0; i < 10; i++) {
Expect.equals(1234567890123456789, foo());
testSmiOverflow();
testModPow(); // //# modPow: ok
testModInverse();
testGcd();
}
}

View file

@ -0,0 +1,471 @@
// Copyright (c) 2011, 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.
// Testing integers with and without intrinsics.
// VMOptions=
// VMOptions=--no_intrinsify
library integer_arithmetic_test;
import "package:expect/expect.dart";
String toHexString(int value) => value >= 0
? "0x${value.toRadixString(16)}"
: "-0x${value.toRadixString(16).substring(1)}";
addSubParsed(String a, String b, String sum) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_sum = int.parse(sum);
int computed_sum = int_a + int_b;
Expect.equals(int_sum, computed_sum);
String str_sum = toHexString(computed_sum);
Expect.equals(sum.toLowerCase(), str_sum);
int computed_difference1 = int_sum - int_a;
Expect.equals(int_b, computed_difference1);
String str_difference1 = toHexString(computed_difference1);
Expect.equals(b.toLowerCase(), str_difference1);
int computed_difference2 = int_sum - int_b;
Expect.equals(int_a, computed_difference2);
String str_difference2 = toHexString(computed_difference2);
Expect.equals(a.toLowerCase(), str_difference2);
}
testAddSub() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
addSubParsed(zero, zero, zero);
addSubParsed(zero, one, one);
addSubParsed(one, zero, one);
addSubParsed(one, one, "0x2");
addSubParsed(minus_one, minus_one, "-0x2");
addSubParsed("0x123", zero, "0x123");
addSubParsed(zero, "0x123", "0x123");
addSubParsed("0x123", one, "0x124");
addSubParsed(one, "0x123", "0x124");
addSubParsed(
"0xFFFFFFF",
one, // 28 bit overflow.
"0x10000000");
addSubParsed(
"0xFFFFFFFF",
one, // 32 bit overflow.
"0x100000000");
addSubParsed(
"0xFFFFFFFFFFFFFF",
one, // 56 bit overflow.
"0x100000000000000");
addSubParsed(
"0x7FFFFFFFFFFFFFFF",
one, // 64 bit overflow.
"-0x8000000000000000");
addSubParsed(
minus_one,
one, // 64 bit overflow.
zero);
addSubParsed(
"0x8000000", // 28 bit overflow.
"0x8000000",
"0x10000000");
addSubParsed(
"0x80000000", // 32 bit overflow.
"0x80000000",
"0x100000000");
addSubParsed(
"0x80000000000000", // 56 bit overflow.
"0x80000000000000",
"0x100000000000000");
addSubParsed(
"-0x8000000000000000", // 64 bit overflow.
"-0x8000000000000000",
zero);
addSubParsed("-0x123", minus_one, "-0x124");
addSubParsed(minus_one, "-0x123", "-0x124");
addSubParsed(
"-0xFFFFFFF",
minus_one, // 28 bit overflow.
"-0x10000000");
addSubParsed(
"-0xFFFFFFFF",
minus_one, // 32 bit overflow.
"-0x100000000");
addSubParsed(
"-0xFFFFFFFFFFFFFF",
minus_one, // 56 bit overflow.
"-0x100000000000000");
addSubParsed(
"-0x8000000000000000",
minus_one, // 64 bit overflow.
"0x7FFFFFFFFFFFFFFF");
addSubParsed(
"-0x8000000", // 28 bit overflow.
"-0x8000000",
"-0x10000000");
addSubParsed(
"-0x80000000", // 32 bit overflow.
"-0x80000000",
"-0x100000000");
addSubParsed(
"-0x80000000000000", // 56 bit overflow.
"-0x80000000000000",
"-0x100000000000000");
addSubParsed(
"-0x8000000000000000", // 64 bit overflow.
"-0x8000000000000000",
"0x0");
addSubParsed("0xB", "-0x7", "0x4");
addSubParsed("-0xB", "-0x7", "-0x12");
addSubParsed("0xB", "0x7", "0x12");
addSubParsed("-0xB", "0x7", "-0x4");
addSubParsed("-0x7", "0xB", "0x4");
addSubParsed("-0x7", "-0xB", "-0x12");
addSubParsed("0x7", "0xB", "0x12");
addSubParsed("0x7", "-0xB", "-0x4");
}
shiftLeftParsed(String a, int amount, String result,
{String? result_back_shifted}) {
result_back_shifted ??= a;
int int_a = int.parse(a);
int int_result = int.parse(result);
int int_result_back_shifted = int.parse(result_back_shifted);
int shifted = int_a << amount;
Expect.equals(int_result, shifted);
String str_shifted = toHexString(shifted);
Expect.equals(result.toLowerCase(), str_shifted);
int back_shifted = shifted >> amount;
Expect.equals(int_result_back_shifted, back_shifted);
String str_back_shifted = toHexString(back_shifted);
Expect.equals(result_back_shifted.toLowerCase(), str_back_shifted);
}
testLeftShift() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
shiftLeftParsed(zero, 0, zero);
shiftLeftParsed(one, 0, one);
shiftLeftParsed("0x1234", 0, "0x1234");
shiftLeftParsed(zero, 100000, zero);
shiftLeftParsed(one, 1, "0x2");
shiftLeftParsed(one, 28, "0x10000000");
shiftLeftParsed(one, 32, "0x100000000");
shiftLeftParsed(one, 64, zero, result_back_shifted: zero);
shiftLeftParsed("0x5", 28, "0x50000000");
shiftLeftParsed("0x5", 32, "0x500000000");
shiftLeftParsed("0x5", 56, "0x500000000000000");
shiftLeftParsed("0x5", 64, zero, result_back_shifted: zero);
shiftLeftParsed("0x5", 128, zero, result_back_shifted: zero);
shiftLeftParsed("0x5", 27, "0x28000000");
shiftLeftParsed("0x5", 31, "0x280000000");
shiftLeftParsed("0x5", 55, "0x280000000000000");
shiftLeftParsed("0x5", 63, "-0x8000000000000000",
result_back_shifted: "-0x1");
shiftLeftParsed("0x5", 127, zero, result_back_shifted: zero);
shiftLeftParsed("0x8000001", 1, "0x10000002");
shiftLeftParsed("0x80000001", 1, "0x100000002");
shiftLeftParsed("0x8000000000000001", 1, "0x2", result_back_shifted: "0x1");
shiftLeftParsed("0x8000001", 29, "0x100000020000000");
shiftLeftParsed("0x80000001", 33, "0x200000000", result_back_shifted: "0x1");
shiftLeftParsed("0x8000000000000001", 65, zero, result_back_shifted: zero);
shiftLeftParsed("0x7fffffffffffffff", 1, "-0x2", result_back_shifted: "-0x1");
shiftLeftParsed("0x7fffffffffffffff", 29, "-0x20000000",
result_back_shifted: "-0x1");
shiftLeftParsed(minus_one, 0, minus_one);
shiftLeftParsed("-0x1234", 0, "-0x1234");
shiftLeftParsed(minus_one, 1, "-0x2");
shiftLeftParsed(minus_one, 28, "-0x10000000");
shiftLeftParsed(minus_one, 32, "-0x100000000");
shiftLeftParsed(minus_one, 64, zero, result_back_shifted: zero);
shiftLeftParsed("-0x5", 28, "-0x50000000");
shiftLeftParsed("-0x5", 32, "-0x500000000");
shiftLeftParsed("-0x5", 64, zero, result_back_shifted: zero);
shiftLeftParsed("-0x5", 27, "-0x28000000");
shiftLeftParsed("-0x5", 31, "-0x280000000");
shiftLeftParsed("-0x5", 63, "-0x8000000000000000",
result_back_shifted: minus_one);
shiftLeftParsed("-0x8000001", 1, "-0x10000002");
shiftLeftParsed("-0x80000001", 1, "-0x100000002");
shiftLeftParsed("-0x8000001", 29, "-0x100000020000000");
shiftLeftParsed("-0x80000001", 33, "-0x200000000",
result_back_shifted: "-0x1");
shiftLeftParsed("-0x7fffffffffffffff", 1, "0x2", result_back_shifted: "0x1");
shiftLeftParsed("-0x7fffffffffffffff", 65, zero, result_back_shifted: zero);
shiftLeftParsed("-0x8000000000000000", 1, zero, result_back_shifted: zero);
shiftLeftParsed("-0x8000000000000000", 29, zero, result_back_shifted: zero);
}
shiftRightParsed(String a, int amount, String result) {
int int_a = int.parse(a);
int int_result = int.parse(result);
int shifted = int_a >> amount;
Expect.equals(int_result, shifted);
String str_shifted = toHexString(shifted);
Expect.equals(result.toLowerCase(), str_shifted);
}
testRightShift() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
shiftRightParsed(one, 1, zero);
shiftRightParsed(minus_one, 1, minus_one);
shiftRightParsed("-0x2", 1, minus_one);
shiftRightParsed("0x12345678", 29, zero);
shiftRightParsed("-0x12345678", 29, minus_one);
shiftRightParsed("-0x12345678", 100, minus_one);
shiftRightParsed("0x5", 1, "0x2");
shiftRightParsed("0x5", 2, "0x1");
shiftRightParsed("-0x5", 1, "-0x3");
shiftRightParsed("-0x5", 2, "-0x2");
shiftRightParsed("0x10000001", 28, one);
shiftRightParsed("0x100000001", 32, one);
shiftRightParsed("0x1000000000000001", 60, one);
shiftRightParsed("0x1000000000000001", 64, zero);
shiftRightParsed("-0x10000001", 28, "-0x2");
shiftRightParsed("-0x100000001", 32, "-0x2");
shiftRightParsed("-0x1000000000000001", 64, minus_one);
shiftRightParsed("0x30000000", 29, one);
shiftRightParsed("0x300000000", 33, one);
shiftRightParsed("0x3000000000000000", 61, one);
shiftRightParsed("0x3000000000000000", 65, zero);
shiftRightParsed("-0x30000000", 29, "-0x2");
shiftRightParsed("-0x300000000", 33, "-0x2");
shiftRightParsed("-0x3000000000000000", 60, "-0x3");
shiftRightParsed("-0x3000000000000000", 65, minus_one);
}
bitAndParsed(String a, String b, String result) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_result = int.parse(result);
int anded = int_a & int_b;
Expect.equals(int_result, anded);
String str_anded = toHexString(anded);
Expect.equals(result.toLowerCase(), str_anded);
int anded2 = int_b & int_a;
Expect.equals(int_result, anded2);
String str_anded2 = toHexString(anded2);
Expect.equals(result.toLowerCase(), str_anded2);
}
testBitAnd() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
bitAndParsed(one, zero, zero);
bitAndParsed(one, one, one);
bitAndParsed(minus_one, zero, zero);
bitAndParsed(minus_one, one, one);
bitAndParsed(minus_one, minus_one, minus_one);
bitAndParsed("0x5", "0x3", one);
bitAndParsed("0x5", minus_one, "0x5");
bitAndParsed("0x50000000", one, zero);
bitAndParsed("0x50000000", minus_one, "0x50000000");
bitAndParsed("0x500000000", one, zero);
bitAndParsed("0x500000000", minus_one, "0x500000000");
bitAndParsed("0x5000000000000000", one, zero);
bitAndParsed("0x5000000000000000", minus_one, "0x5000000000000000");
bitAndParsed("-0x50000000", "-0x50000000", "-0x50000000");
bitAndParsed("-0x500000000", "-0x500000000", "-0x500000000");
bitAndParsed("0x12345678", "0xFFFFFFF", "0x2345678");
bitAndParsed("0x123456789", "0xFFFFFFFF", "0x23456789");
bitAndParsed("-0x10000000", "0xFFFFFFF", "0x0");
bitAndParsed("-0x100000000", "0xFFFFFFFF", "0x0");
bitAndParsed("-0x10000001", "0xFFFFFFF", "0xFFFFFFF");
bitAndParsed("-0x100000001", "0xFFFFFFFF", "0xFFFFFFFF");
bitAndParsed("-0x10000001", "0x3FFFFFFF", "0x2FFFFFFF");
bitAndParsed("-0x100000001", "0x3FFFFFFFF", "0x2FFFFFFFF");
bitAndParsed("-0x100000000000000", "0xFFFFFFFFFFFFFF", "0x0");
bitAndParsed(
"-0x1000000000000000", "0xFFFFFFFFFFFFFFFF", "-0x1000000000000000");
bitAndParsed("-0x300000000000000", "0xFFFFFFFFFFFFFFF", "0xD00000000000000");
bitAndParsed(
"-0x3000000000000000", "0xFFFFFFFFFFFFFFFF", "-0x3000000000000000");
bitAndParsed("-0x10000000", "-0x10000000", "-0x10000000");
bitAndParsed("-0x100000000", "-0x100000000", "-0x100000000");
bitAndParsed(
"-0x100000000000000", "-0x100000000000000", "-0x100000000000000");
bitAndParsed(
"-0x1000000000000000", "-0x1000000000000000", "-0x1000000000000000");
bitAndParsed("-0x3", "-0x2", "-0x4");
bitAndParsed("-0x10000000", "-0x10000001", "-0x20000000");
bitAndParsed("-0x100000000", "-0x100000001", "-0x200000000");
bitAndParsed(
"-0x100000000000000", "-0x100000000000001", "-0x200000000000000");
bitAndParsed(
"-0x1000000000000000", "-0x1000000000000001", "-0x2000000000000000");
}
bitOrParsed(String a, String b, String result) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_result = int.parse(result);
int ored = int_a | int_b;
Expect.equals(int_result, ored);
String str_ored = toHexString(ored);
Expect.equals(result.toLowerCase(), str_ored);
int ored2 = int_b | int_a;
Expect.equals(int_result, ored2);
String str_ored2 = toHexString(ored2);
Expect.equals(result.toLowerCase(), str_ored2);
}
testBitOr() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
bitOrParsed(one, zero, one);
bitOrParsed(one, one, one);
bitOrParsed(minus_one, zero, minus_one);
bitOrParsed(minus_one, one, minus_one);
bitOrParsed(minus_one, minus_one, minus_one);
bitOrParsed("-0x3", one, "-0x3");
bitOrParsed("0x5", "0x3", "0x7");
bitOrParsed("0x5", minus_one, minus_one);
bitOrParsed("0x5", zero, "0x5");
bitOrParsed("0x50000000", one, "0x50000001");
bitOrParsed("0x50000000", minus_one, minus_one);
bitOrParsed("0x500000000", one, "0x500000001");
bitOrParsed("0x500000000", minus_one, minus_one);
bitOrParsed("0x5000000000000000", one, "0x5000000000000001");
bitOrParsed("0x5000000000000000", minus_one, minus_one);
bitOrParsed("-0x50000000", "-0x50000000", "-0x50000000");
bitOrParsed("-0x500000000", "-0x500000000", "-0x500000000");
bitOrParsed("0x12345678", "0xFFFFFFF", "0x1FFFFFFF");
bitOrParsed("0x123456789", "0xFFFFFFFF", "0x1FFFFFFFF");
bitOrParsed("-0x10000000", "0xFFFFFFF", "-0x1");
bitOrParsed("-0x100000000", "0xFFFFFFFF", "-0x1");
bitOrParsed("-0x10000001", "0xFFFFFFF", "-0x10000001");
bitOrParsed("-0x100000001", "0xFFFFFFFF", "-0x100000001");
bitOrParsed("-0x10000001", "0x3FFFFFFF", "-0x1");
bitOrParsed("-0x100000001", "0x3FFFFFFFF", "-0x1");
bitOrParsed("-0x1000000000000001", "0x3FFFFFFFFFFFFFFF", "-0x1");
bitOrParsed("-0x100000000000000", "0xFFFFFFFFFFFFFF", "-0x1");
bitOrParsed("-0x1000000000000000", "0xFFFFFFFFFFFFFFF", "-0x1");
bitOrParsed("-0x300000000000000", "0xFFFFFFFFFFFFFFF", "-0x1");
bitOrParsed("-0x3000000000000000", "0xFFFFFFFFFFFFFFFF", "-0x1");
bitOrParsed("-0x10000000", "-0x10000000", "-0x10000000");
bitOrParsed("-0x100000000", "-0x100000000", "-0x100000000");
bitOrParsed("-0x100000000000000", "-0x100000000000000", "-0x100000000000000");
bitOrParsed(
"-0x1000000000000000", "-0x1000000000000000", "-0x1000000000000000");
bitOrParsed("-0x10000000", "-0x10000001", "-0x1");
bitOrParsed("-0x100000000", "-0x100000001", "-0x1");
bitOrParsed("-0x100000000000000", "-0x100000000000001", "-0x1");
bitOrParsed("-0x1000000000000000", "-0x1000000000000001", "-0x1");
bitOrParsed("-0x1000000000000000", "-0x1", "-0x1");
}
bitXorParsed(String a, String b, String result) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_result = int.parse(result);
int xored = int_a ^ int_b;
Expect.equals(int_result, xored);
String str_xored = toHexString(xored);
Expect.equals(result.toLowerCase(), str_xored);
int xored2 = int_b ^ int_a;
Expect.equals(int_result, xored2);
String str_xored2 = toHexString(xored2);
Expect.equals(result.toLowerCase(), str_xored2);
int xored3 = int_a ^ xored2;
Expect.equals(int_b, xored3);
String str_xored3 = toHexString(xored3);
Expect.equals(b.toLowerCase(), str_xored3);
}
testBitXor() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
bitXorParsed(one, zero, one);
bitXorParsed(one, one, zero);
bitXorParsed(minus_one, zero, minus_one);
bitXorParsed(minus_one, one, "-0x2");
bitXorParsed(minus_one, minus_one, zero);
bitXorParsed("0x5", "0x3", "0x6");
bitXorParsed("0x5", minus_one, "-0x6");
bitXorParsed("0x5", zero, "0x5");
bitXorParsed(minus_one, "-0x8", "0x7");
bitXorParsed("0x50000000", one, "0x50000001");
bitXorParsed("0x50000000", minus_one, "-0x50000001");
bitXorParsed("0x500000000", one, "0x500000001");
bitXorParsed("0x500000000", minus_one, "-0x500000001");
bitXorParsed("0x5000000000000000", one, "0x5000000000000001");
bitXorParsed("0x5000000000000000", minus_one, "-0x5000000000000001");
bitXorParsed("-0x50000000", "-0x50000000", zero);
bitXorParsed("-0x500000000", "-0x500000000", zero);
bitXorParsed("0x12345678", "0xFFFFFFF", "0x1DCBA987");
bitXorParsed("0x123456789", "0xFFFFFFFF", "0x1DCBA9876");
bitXorParsed("-0x10000000", "0xFFFFFFF", "-0x1");
bitXorParsed("-0x100000000", "0xFFFFFFFF", "-0x1");
bitXorParsed("-0x10000001", "0xFFFFFFF", "-0x20000000");
bitXorParsed("-0x100000001", "0xFFFFFFFF", "-0x200000000");
bitXorParsed("-0x10000001", "0x3FFFFFFF", "-0x30000000");
bitXorParsed("-0x100000001", "0x3FFFFFFFF", "-0x300000000");
bitXorParsed(
"-0x1000000000000001", "0x3FFFFFFFFFFFFFFF", "-0x3000000000000000");
bitXorParsed("-0x100000000000000", "0xFFFFFFFFFFFFFF", "-0x1");
bitXorParsed("-0x1000000000000000", "0xFFFFFFFFFFFFFFF", "-0x1");
bitXorParsed("-0x300000000000000", "0xFFFFFFFFFFFFFFF", "-0xD00000000000001");
bitXorParsed("-0x3000000000000000", "-0x1", "0x2FFFFFFFFFFFFFFF");
bitXorParsed("-0x10000000", "-0x10000000", zero);
bitXorParsed("-0x100000000", "-0x100000000", zero);
bitXorParsed("-0x100000000000000", "-0x100000000000000", zero);
bitXorParsed("-0x1000000000000000", "-0x1000000000000000", zero);
bitXorParsed("-0x10000000", "-0x10000001", "0x1FFFFFFF");
bitXorParsed("-0x100000000", "-0x100000001", "0x1FFFFFFFF");
bitXorParsed("-0x100000000000000", "-0x100000000000001", "0x1FFFFFFFFFFFFFF");
bitXorParsed(
"-0x1000000000000000", "-0x1000000000000001", "0x1FFFFFFFFFFFFFFF");
}
bitNotParsed(String a, String result) {
int int_a = int.parse(a);
int int_result = int.parse(result);
int inverted = ~int_a;
Expect.equals(int_result, inverted);
String str_inverted = toHexString(inverted);
Expect.equals(result.toLowerCase(), str_inverted);
int back = ~inverted;
Expect.equals(int_a, back);
String str_back = toHexString(back);
Expect.equals(a.toLowerCase(), str_back);
}
testBitNot() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
bitNotParsed(zero, minus_one);
bitNotParsed(one, "-0x2");
bitNotParsed("0x5", "-0x6");
bitNotParsed("0x50000000", "-0x50000001");
bitNotParsed("0xFFFFFFF", "-0x10000000");
bitNotParsed("0xFFFFFFFF", "-0x100000000");
bitNotParsed("0xFFFFFFFFFFFFFF", "-0x100000000000000");
bitNotParsed("0x7FFFFFFFFFFFFFFF", "-0x8000000000000000");
bitNotParsed("-0x1", "0x0");
}
main() {
testAddSub();
testLeftShift();
testRightShift();
testBitAnd();
testBitOr();
testBitXor();
testBitNot();
}

View file

@ -0,0 +1,66 @@
// Copyright (c) 2011, 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.
// Testing integers with and without intrinsics.
// VMOptions=
// VMOptions=--no_intrinsify
library integer_arithmetic_test;
import "package:expect/expect.dart";
divRemParsed(String a, String b, String quotient, String remainder) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_quotient = int.parse(quotient);
int int_remainder = int.parse(remainder);
int computed_quotient = int_a ~/ int_b;
Expect.equals(int_quotient, computed_quotient);
String str_quotient = computed_quotient >= 0
? "0x${computed_quotient.toRadixString(16)}"
: "-0x${computed_quotient.toRadixString(16).substring(1)}";
Expect.equals(quotient.toLowerCase(), str_quotient);
int computed_remainder = int_a.remainder(int_b) as int;
Expect.equals(int_remainder, computed_remainder);
String str_remainder = computed_remainder >= 0
? "0x${computed_remainder.toRadixString(16)}"
: "-0x${computed_remainder.toRadixString(16).substring(1)}";
Expect.equals(remainder.toLowerCase(), str_remainder);
}
testDivideRemainder() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
divRemParsed(one, one, one, zero);
divRemParsed(zero, one, zero, zero);
divRemParsed(minus_one, one, minus_one, zero);
divRemParsed(one, "0x2", zero, one);
divRemParsed(minus_one, "0x7", zero, minus_one);
divRemParsed("0xB", "0x7", one, "0x4");
divRemParsed("0x12345678", "0x7", "0x299C335", "0x5");
divRemParsed("-0x12345678", "0x7", "-0x299C335", "-0x5");
divRemParsed("0x12345678", "-0x7", "-0x299C335", "0x5");
divRemParsed("-0x12345678", "-0x7", "0x299C335", "-0x5");
divRemParsed("0x7", "0x12345678", zero, "0x7");
divRemParsed("-0x7", "0x12345678", zero, "-0x7");
divRemParsed("-0x7", "-0x12345678", zero, "-0x7");
divRemParsed("0x7", "-0x12345678", zero, "0x7");
divRemParsed("0x12345678", "0x7", "0x299C335", "0x5");
divRemParsed("-0x12345678", "0x7", "-0x299C335", "-0x5");
divRemParsed("0x12345678", "-0x7", "-0x299C335", "0x5");
divRemParsed("-0x12345678", "-0x7", "0x299C335", "-0x5");
divRemParsed("9223372036854775807", "0x7", "0x1249249249249249", "0x0");
divRemParsed("9223372036854775807", "-0x7", "-0x1249249249249249", "0x0");
divRemParsed("-9223372036854775807", "0x7", "-0x1249249249249249", "0x0");
divRemParsed("-9223372036854775807", "-0x7", "0x1249249249249249", "0x0");
divRemParsed("-9223372036854775808", "-1", "-0x8000000000000000", "0x0"); //# 01: ok
divRemParsed("-9223372036854775808", "0x7", "-0x1249249249249249", "-0x1");
divRemParsed("-9223372036854775808", "-0x7", "0x1249249249249249", "-0x1");
}
main() {
testDivideRemainder();
}

View file

@ -0,0 +1,81 @@
// Copyright (c) 2011, 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.
// Testing integers with and without intrinsics.
// VMOptions=
// VMOptions=--no_intrinsify
library integer_arithmetic_test;
import "package:expect/expect.dart";
mulDivParsed(String a, String b, String product,
{String? expected_quotient1, String? expected_quotient2}) {
int int_a = int.parse(a);
int int_b = int.parse(b);
int int_product = int.parse(product);
int computed_product = int_a * int_b;
Expect.equals(int_product, computed_product);
String str_product = computed_product >= 0
? "0x${computed_product.toRadixString(16)}"
: "-0x${(-computed_product).toRadixString(16)}";
Expect.equals(product.toLowerCase(), str_product);
int computed_product2 = int_b * int_a;
Expect.equals(int_product, computed_product2);
String str_product2 = computed_product2 >= 0
? "0x${computed_product2.toRadixString(16)}"
: "-0x${(-computed_product2).toRadixString(16)}";
Expect.equals(product.toLowerCase(), str_product2);
if (int_a != 0) {
expected_quotient1 ??= b;
int int_expected_quotient1 = int.parse(expected_quotient1);
int computed_quotient1 = int_product ~/ int_a;
Expect.equals(int_expected_quotient1, computed_quotient1);
String str_quotient1 = computed_quotient1 >= 0
? "0x${computed_quotient1.toRadixString(16)}"
: "-0x${(-computed_quotient1).toRadixString(16)}";
Expect.equals(expected_quotient1.toLowerCase(), str_quotient1);
}
if (int_b != 0) {
expected_quotient2 ??= a;
int int_expected_quotient2 = int.parse(expected_quotient2);
int computed_quotient2 = int_product ~/ int_b;
Expect.equals(int_expected_quotient2, computed_quotient2);
String str_quotient2 = computed_quotient2 >= 0
? "0x${computed_quotient2.toRadixString(16)}"
: "-0x${(-computed_quotient2).toRadixString(16)}";
Expect.equals(expected_quotient2.toLowerCase(), str_quotient2);
}
}
testMultiplyDivide() {
String zero = "0x0";
String one = "0x1";
String minus_one = "-0x1";
mulDivParsed(zero, zero, zero);
mulDivParsed(one, one, one);
mulDivParsed(one, zero, zero);
mulDivParsed(zero, one, zero);
mulDivParsed(one, minus_one, minus_one);
mulDivParsed(minus_one, minus_one, one);
mulDivParsed("0x42", one, "0x42");
mulDivParsed("0x42", "0x2", "0x84");
mulDivParsed("0xFFFF", "0x2", "0x1FFFE");
mulDivParsed("0x3", "0x5", "0xF");
mulDivParsed("0xFFFFF", "0x5", "0x4FFFFB");
mulDivParsed("0xFFFFFFF", "0x5", "0x4FFFFFFB");
mulDivParsed("0xFFFFFFFF", "0x5", "0x4FFFFFFFB");
mulDivParsed("0x7FFFFFFFFFFFFFFF", "0x5", "0x7FFFFFFFFFFFFFFB",
expected_quotient1: zero, expected_quotient2: "0x1999999999999998");
mulDivParsed("0x7FFFFFFFFFFFFFFF", "0x3039", "0x7FFFFFFFFFFFCFC7",
expected_quotient1: zero, expected_quotient2: "0x2A783BE38C73D");
mulDivParsed("0x10000001", "0x5", "0x50000005");
}
main() {
testMultiplyDivide();
}

View file

@ -0,0 +1,87 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
// Test that we accept radix 2 to 36 and that we use lower-case
// letters.
var expected = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z'
];
for (var radix = 2; radix <= 36; radix++) {
for (var i = 0; i < radix; i++) {
Expect.equals(expected[i], i.toRadixString(radix));
}
}
var illegalRadices = [-1, 0, 1, 37];
for (var radix in illegalRadices) {
try {
42.toRadixString(radix);
Expect.fail("Exception expected");
} on ArgumentError catch (e) {
// Nothing to do.
}
}
// Try large numbers (regression test for issue 15316).
var bignums = [
0x80000000,
0x100000000,
0x10000000000000,
0x10000000000001, // 53 significant bits.
0x20000000000000,
0x20000000000002,
0x1000000000000000,
0x1000000000000100,
0x2000000000000000,
0x2000000000000200,
0x8000000000000000, //# 01: ok
0x8000000000000800, //# 02: ok
];
for (var bignum in bignums) {
for (int radix = 2; radix <= 36; radix++) {
String digits = bignum.toRadixString(radix);
int result = int.parse(digits, radix: radix);
Expect.equals(
bignum, result, "${bignum.toRadixString(16)} -> $digits/$radix");
}
}
}

View file

@ -0,0 +1,84 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
/// Test that converting [value] to a string gives [expect].
/// Also test that `-value` gives `"-"+expect`.
test(int value, String expect) {
Expect.equals(expect, value.toString());
Expect.equals(expect, "$value");
Expect.equals(expect, (new StringBuffer()..write(value)).toString());
if (value <= 0) return;
expect = "-$expect";
value = -value;
Expect.equals(expect, value.toString());
Expect.equals(expect, "$value");
Expect.equals(expect, (new StringBuffer()..write(value)).toString());
}
// Very simple tests.
test(0, "0");
test(1, "1");
test(2, "2");
test(5, "5");
// Binary special cases.
// ~2^30.
test(0x3fffffff, "1073741823");
test(0x40000000, "1073741824");
test(0x40000001, "1073741825");
// ~2^31.
test(0x7fffffff, "2147483647");
test(0x80000000, "2147483648");
test(0x80000001, "2147483649");
// ~2^32.
test(0xffffffff, "4294967295");
test(0x100000000, "4294967296");
test(0x100000001, "4294967297");
// ~2^51.
test(0x7ffffffffffff, "2251799813685247");
test(0x8000000000000, "2251799813685248");
test(0x8000000000001, "2251799813685249");
// ~2^52.
test(0xfffffffffffff, "4503599627370495");
test(0x10000000000000, "4503599627370496");
test(0x10000000000001, "4503599627370497");
// ~2^53.
test(0x1fffffffffffff, "9007199254740991");
test(0x20000000000000, "9007199254740992");
test(0x20000000000001, "9007199254740993"); // //# 01: ok
// ~2^62.
test(0x3fffffffffffffff, "4611686018427387903"); // //# 01: continued
test(0x4000000000000000, "4611686018427387904"); // //# 01: continued
test(0x4000000000000001, "4611686018427387905"); // //# 01: continued
// ~2^63.
test(0x7fffffffffffffff, "9223372036854775807"); // //# 01: continued
test(0x8000000000000000, "-9223372036854775808"); // //# 01: continued
test(0x8000000000000001, "-9223372036854775807"); // //# 01: continued
// ~2^64.
test(0xffffffffffffffff, "-1"); // //# 01: continued
// Decimal special cases.
int number = 10;
// Numbers 99..99, 100...00, and 100..01 up to 18 digits.
for (int i = 1; i < 15; i++) {
// Works in dart2js up to 10^15.
test(number - 1, "9" * i);
test(number, "1" + "0" * i);
test(number + 1, "1" + "0" * (i - 1) + "1");
number *= 10;
}
// Fails to represent exactly in dart2js.
for (int i = 15; i < 19; i++) { // //# 01: continued
test(number - 1, "9" * i); // //# 01: continued
test(number, "1" + "0" * i); // //# 01: continued
test(number + 1, "1" + "0" * (i - 1) + "1"); // //# 01: continued
number *= 10; // //# 01: continued
} // //# 01: continued
}

View file

@ -0,0 +1,413 @@
// Copyright (c) 2018, 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.
import "package:expect/expect.dart";
// Tests the constructors of the Invocation class.
main() {
{
var name = "getter";
var invocation = new Invocation.getter(#name);
Expect.isTrue(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isTrue(invocation.isAccessor, "$name:isAccessor");
Expect.isFalse(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
}
{
var name = "setter";
var argument = new Object();
var invocation = new Invocation.setter(const Symbol("name="), argument);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isTrue(invocation.isSetter, "$name:isSetter");
Expect.isTrue(invocation.isAccessor, "$name:isAccessor");
Expect.isFalse(invocation.isMethod, "$name:isMethod");
Expect.equals(const Symbol("name="), invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([argument], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
}
{
var name = ".name()";
var invocation = new Invocation.method(#name, []);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation("$name:", invocation, new Invocation.method(#name, null));
expectInvocation(
"$name:", invocation, new Invocation.method(#name, [], null));
expectInvocation(
"$name:", invocation, new Invocation.method(#name, [], {}));
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, [], []));
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, [], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [], [], null));
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, [], [], {}));
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, null, []));
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, null, null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [], {}));
}
{
var name = ".name(a)";
var argument = new Object();
var invocation = new Invocation.method(#name, [argument]);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([argument], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation(
"$name:", invocation, new Invocation.method(#name, [argument], null));
expectInvocation(
"$name:", invocation, new Invocation.method(#name, [argument], {}));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [], [argument], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [], [argument], {}));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [argument], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [argument], {}));
}
{
var name = ".name(a,b)";
var argument = new Object();
var argument2 = new Object();
var invocation = new Invocation.method(#name, [argument, argument2]);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals(
[argument, argument2], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation("$name:", invocation,
new Invocation.method(#name, [argument, argument2], null));
expectInvocation("$name:", invocation,
new Invocation.method(#name, [argument, argument2], {}));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [], [argument, argument2], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [], [argument, argument2], {}));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [argument, argument2], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, null, [argument, argument2], {}));
}
{
var name = ".name(a,b:)";
var argument = new Object();
var argument2 = new Object();
var invocation =
new Invocation.method(#name, [argument], {#arg: argument2});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([argument], invocation.positionalArguments, "$name:pos");
Expect.mapEquals(
{#arg: argument2}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation(
"$name:",
invocation,
new Invocation.genericMethod(
#name, null, [argument], {#arg: argument2}));
}
{
var name = ".name(a:,b:)";
var argument = new Object();
var argument2 = new Object();
var invocation =
new Invocation.method(#name, [], {#arg: argument, #arg2: argument2});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([], invocation.typeArguments, "$name:types");
Expect.listEquals([], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({#arg: argument, #arg2: argument2},
invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation("$name:", invocation,
new Invocation.method(#name, null, {#arg: argument, #arg2: argument2}));
expectInvocation(
"$name:",
invocation,
new Invocation.genericMethod(
#name, null, [], {#arg: argument, #arg2: argument2}));
expectInvocation(
"$name:",
invocation,
new Invocation.genericMethod(
#name, null, null, {#arg: argument, #arg2: argument2}));
}
{
var name = ".name<i>()";
var invocation = new Invocation.genericMethod(#name, [int], []);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([int], invocation.typeArguments, "$name:types");
Expect.listEquals([], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation(
"$name:", invocation, new Invocation.genericMethod(#name, [int], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], [], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], null, null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], [], {}));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], null, {}));
}
{
var name = ".name<i>(a)";
var argument = new Object();
var invocation = new Invocation.genericMethod(#name, [int], [argument]);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([int], invocation.typeArguments, "$name:types");
Expect.listEquals([argument], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], [argument], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], [argument], {}));
}
{
var name = ".name<i>(a,b)";
var argument = new Object();
var argument2 = new Object();
var invocation =
new Invocation.genericMethod(#name, [int], [argument, argument2]);
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([int], invocation.typeArguments, "$name:types");
Expect.listEquals(
[argument, argument2], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation(
"$name:",
invocation,
new Invocation.genericMethod(
#name, [int], [argument, argument2], null));
expectInvocation("$name:", invocation,
new Invocation.genericMethod(#name, [int], [argument, argument2], {}));
}
{
var name = ".name<i>(a,b:)";
var argument = new Object();
var argument2 = new Object();
var invocation = new Invocation.genericMethod(
#name, [int], [argument], {#arg: argument2});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([int], invocation.typeArguments, "$name:types");
Expect.listEquals([argument], invocation.positionalArguments, "$name:pos");
Expect.mapEquals(
{#arg: argument2}, invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
}
{
var name = ".name<i>(a:,b:)";
var argument = new Object();
var argument2 = new Object();
var invocation = new Invocation.genericMethod(
#name, [int], [], {#arg: argument, #arg2: argument2});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals([int], invocation.typeArguments, "$name:types");
Expect.listEquals([], invocation.positionalArguments, "$name:pos");
Expect.mapEquals({#arg: argument, #arg2: argument2},
invocation.namedArguments, "$name: named");
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
expectInvocation(
"$name:",
invocation,
new Invocation.genericMethod(
#name, [int], null, {#arg: argument, #arg2: argument2}));
}
{
// Many arguments.
var name = ".name<..>(..,..:)";
var argument = new Object();
var argument2 = new Object();
Type intList = new TypeHelper<List<int>>().type;
var invocation = new Invocation.genericMethod(
#name,
[int, double, intList],
[argument, argument2, null, argument],
{#arg: argument, #arg2: argument2, #arg3: null, #arg4: argument});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals(
[int, double, intList], invocation.typeArguments, "$name:types");
Expect.listEquals([argument, argument2, null, argument],
invocation.positionalArguments, "$name:pos");
Expect.mapEquals(
{#arg: argument, #arg2: argument2, #arg3: null, #arg4: argument},
invocation.namedArguments);
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
}
{
// Accepts iterables, not just lists.
var name = "iterables";
var argument = new Object();
var argument2 = new Object();
Type intList = new TypeHelper<List<int>>().type;
var invocation = new Invocation.genericMethod(
#name,
[int, double, intList].where(kTrue),
[argument, argument2, null, argument].where(kTrue),
{#arg: argument, #arg2: argument2, #arg3: null, #arg4: argument});
Expect.isFalse(invocation.isGetter, "$name:isGetter");
Expect.isFalse(invocation.isSetter, "$name:isSetter");
Expect.isFalse(invocation.isAccessor, "$name:isAccessor");
Expect.isTrue(invocation.isMethod, "$name:isMethod");
Expect.equals(#name, invocation.memberName, "$name:name");
Expect.listEquals(
[int, double, intList], invocation.typeArguments, "$name:types");
Expect.listEquals([argument, argument2, null, argument],
invocation.positionalArguments, "$name:pos");
Expect.mapEquals(
{#arg: argument, #arg2: argument2, #arg3: null, #arg4: argument},
invocation.namedArguments);
checkUnmodifiableList("$name types", invocation.typeArguments);
checkUnmodifiableList("$name positional", invocation.positionalArguments);
checkUnmodifiableMap("$name named", invocation.namedArguments);
}
}
void checkUnmodifiableList(String name, List<Object?> list) {
if (list.isNotEmpty) {
Expect.throws(() {
list[0] = null;
}, (_) => true, "$name: list not unmodifiable");
}
Expect.throws(() {
list.add(null);
}, (_) => true, "$name: list not unmodifiable");
}
void checkUnmodifiableMap(String name, Map<Symbol, Object?> map) {
Expect.throws(() {
map[#key] = null;
}, (_) => true, "$name: map not unmodifiable");
}
class TypeHelper<T> {
Type get type => T;
}
expectInvocation(String name, Invocation expect, Invocation actual) {
Expect.equals(expect.isGetter, actual.isGetter, "$name:isGetter");
Expect.equals(expect.isSetter, actual.isSetter, "$name:isSetter");
Expect.equals(expect.isAccessor, actual.isAccessor, "$name:isAccessor");
Expect.equals(actual.isGetter || actual.isSetter, actual.isAccessor);
Expect.equals(expect.isMethod, actual.isMethod, "$name:isMethod");
Expect.isTrue(actual.isMethod || actual.isGetter || actual.isSetter);
Expect.isFalse(actual.isMethod && actual.isGetter);
Expect.isFalse(actual.isMethod && actual.isSetter);
Expect.isFalse(actual.isSetter && actual.isGetter);
Expect.equals(expect.memberName, actual.memberName, "$name:memberName");
Expect.listEquals(expect.typeArguments, actual.typeArguments, "$name:types");
Expect.listEquals(
expect.positionalArguments, actual.positionalArguments, "$name:pos");
Expect.mapEquals(expect.namedArguments, actual.namedArguments, "$name:named");
checkUnmodifiableList(name, actual.typeArguments);
checkUnmodifiableList(name, actual.positionalArguments);
checkUnmodifiableMap(name, actual.namedArguments);
}
bool kTrue(_) => true;

View file

@ -0,0 +1,61 @@
// Copyright (c) 2012, 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.
// Dart test program for the "is" type test operator.
import "package:expect/expect.dart";
check(args) {
var list = args[0];
var string = args[1];
var nullObject = args[2];
Expect.isTrue(list is Object);
Expect.isTrue(list is List);
Expect.isTrue(list is Iterable);
Expect.isFalse(list is Comparable);
Expect.isFalse(list is Pattern);
Expect.isFalse(list is String);
Expect.isFalse(list is! List);
Expect.isFalse(list is! Iterable);
Expect.isTrue(list is! Comparable);
Expect.isTrue(list is! Pattern);
Expect.isTrue(list is! String);
Expect.isTrue(string is Object);
Expect.isFalse(string is List);
Expect.isFalse(string is Iterable);
Expect.isTrue(string is Comparable);
Expect.isTrue(string is Pattern);
Expect.isTrue(string is String);
Expect.isTrue(string is! List);
Expect.isTrue(string is! Iterable);
Expect.isFalse(string is! Comparable);
Expect.isFalse(string is! Pattern);
Expect.isFalse(string is! String);
Expect.isTrue(nullObject is Object);
Expect.isFalse(nullObject is List);
Expect.isFalse(nullObject is Iterable);
Expect.isFalse(nullObject is Comparable);
Expect.isFalse(nullObject is Pattern);
Expect.isFalse(nullObject is String);
Expect.isTrue(nullObject is! List);
Expect.isTrue(nullObject is! Iterable);
Expect.isTrue(nullObject is! Comparable);
Expect.isTrue(nullObject is! Pattern);
Expect.isTrue(nullObject is! String);
}
main() {
// Try to make it hard for an optimizing compiler to inline the
// tests.
check([[], 'string', null]);
// Try to make it even harder.
var string = new String.fromCharCodes([new DateTime.now().year % 100 + 1]);
check([string.codeUnits, string, null]);
}

View file

@ -0,0 +1,38 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
// Tests for the contains methods on lists.
class A {
const A();
}
class B extends A {
const B();
}
main() {
var list = <B>[new B()];
var set = new Set<B>();
set.add(new B());
var iterable1 = list.map((x) => x);
var iterable2 = list.take(1);
var list2 = const <B>[const B()];
var iterable3 = list2.map((x) => x);
var iterable4 = list2.take(1);
var iterables = [
list,
set,
iterable1,
iterable2,
list2,
iterable3,
iterable4
];
for (var iterable in iterables) {
Expect.isFalse(iterable.contains(new A()));
}
}

View file

@ -0,0 +1,48 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
// Tests for the contains methods on lists.
test(list, notInList) {
testList(list) {
for (int i = 0; i < list.length; i++) {
var elem = list[i];
Expect.isTrue(list.contains(list[i]), "$list.contains($elem)");
}
Expect.isFalse(list.contains(notInList), "!$list.contains($notInList)");
}
List fixedList = new List(list.length);
List growList = new List();
for (int i = 0; i < list.length; i++) {
fixedList[i] = list[i];
growList.add(list[i]);
}
testList(list);
testList(fixedList);
testList(growList);
}
class C {
const C();
}
class Niet {
bool operator ==(other) => false;
}
main() {
test(const <String?>["a", "b", "c", null], "d");
test(const <int?>[1, 2, 3, null], 0);
test(const <bool>[true, false], null);
test(const <C?>[const C(), const C(), null], new C());
test(<C?>[new C(), new C(), new C(), null], new C());
test(const <double>[0.0, 1.0, 5e-324, 1e+308, double.infinity], 2.0);
Expect.isTrue(const <double>[-0.0].contains(0.0));
Expect.isFalse(const <double>[double.nan].contains(double.nan));
var niet = new Niet();
Expect.isFalse([niet].contains(niet));
}

View file

@ -0,0 +1,39 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5, 6];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(1, list1.elementAt(0));
Expect.equals(2, list1.elementAt(1));
Expect.equals(3, list1.elementAt(2));
list1.elementAt("2"); //# static: compile-time error
Expect.throwsArgumentError(() => list1.elementAt(-1));
Expect.throwsRangeError(() => list1.elementAt(3));
Expect.equals(4, list2.elementAt(0));
Expect.equals(5, list2.elementAt(1));
Expect.equals(6, list2.elementAt(2));
list2.elementAt("2"); //# static: compile-time error
Expect.throwsArgumentError(() => list2.elementAt(-1));
Expect.throwsRangeError(() => list2.elementAt(3));
Expect.isTrue(set1.contains(set1.elementAt(0)));
Expect.isTrue(set1.contains(set1.elementAt(1)));
Expect.isTrue(set1.contains(set1.elementAt(2)));
Expect.throwsArgumentError(() => set1.elementAt(-1));
Expect.throwsRangeError(() => set1.elementAt(3));
set2.elementAt("2"); //# static: compile-time error
Expect.throwsArgumentError(() => set2.elementAt(-1));
Expect.throwsRangeError(() => set2.elementAt(0));
Expect.throwsRangeError(() => set2.elementAt(1));
}

View file

@ -0,0 +1,70 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
main() {
testEmpty(name, Iterable<int> it, [depth = 2]) {
Expect.isTrue(it.isEmpty, name);
Expect.isFalse(it.isNotEmpty, name);
Expect.equals(0, it.length, name);
Expect.isFalse(it.contains(null), name);
Expect.isFalse(it.any((x) => true), name);
Expect.isTrue(it.every((x) => false), name);
Expect.throwsStateError(() => it.first, name);
Expect.throwsStateError(() => it.last, name);
Expect.throwsStateError(() => it.single, name);
Expect.throwsRangeError(() => it.elementAt(0), name);
Expect.throwsStateError(() => it.reduce((a, b) => a), name);
Expect.throwsStateError(() => it.singleWhere((_) => true), name);
Expect.equals(42, it.fold(42, (a, b) => "not 42"), name);
Expect.equals(42, it.firstWhere((v) => true, orElse: () => 42), name);
Expect.equals(42, it.lastWhere((v) => true, orElse: () => 42), name);
Expect.equals("", it.join("separator"), name);
Expect.equals("()", it.toString(), name);
Expect.listEquals([], it.toList(), name);
Expect.listEquals([], it.toList(growable: false), name);
Expect.listEquals([], it.toList(growable: true), name);
Expect.equals(0, it.toSet().length, name);
// Doesn't throw:
it.forEach((v) => throw v);
for (var v in it) {
throw v;
}
// Check that returned iterables are also empty.
if (depth > 0) {
testEmpty("$name-map", it.map((x) => x), depth - 1);
testEmpty("$name-where", it.where((x) => true), depth - 1);
testEmpty("$name-expand", it.expand((x) => [x]), depth - 1);
testEmpty("$name-skip", it.skip(1), depth - 1);
testEmpty("$name-take", it.take(2), depth - 1);
testEmpty("$name-skipWhile", it.skipWhile((v) => false), depth - 1);
testEmpty("$name-takeWhile", it.takeWhile((v) => true), depth - 1);
}
}
testType(name, it, [depth = 2]) {
Expect.isTrue(it is Iterable<int>, name);
Expect.isFalse(it is Iterable<String>, name);
if (depth > 0) {
testType("$name-where", it.where((_) => true), depth - 1);
testType("$name-skip", it.skip(1), depth - 1);
testType("$name-take", it.take(1), depth - 1);
testType("$name-skipWhile", it.skipWhile((_) => false), depth - 1);
testType("$name-takeWhile", it.takeWhile((_) => true), depth - 1);
testType("$name-toList", it.toList(), depth - 1);
testType("$name-toList", it.toList(growable: false), depth - 1);
testType("$name-toList", it.toList(growable: true), depth - 1);
testType("$name-toSet", it.toSet(), depth - 1);
}
}
test(name, it) {
testEmpty(name, it);
testType(name, it);
}
test("const", const Iterable<int>.empty());
test("new", new Iterable<int>.empty());
}

View file

@ -0,0 +1,74 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
import 'dart:collection';
class MyList extends ListBase {
List list;
MyList(this.list);
get length => list.length;
set length(val) {
list.length = val;
}
operator [](index) => list[index];
operator []=(index, val) => list[index] = val;
String toString() => "[" + join(", ") + "]";
}
main() {
test(expectation, iterable) {
Expect.listEquals(expectation, iterable.toList());
}
// Function not called on empty iterable.
test(
[],
[].expand((x) {
throw "not called";
}));
// Creating the iterable doesn't call the function.
[1].expand((x) {
throw "not called";
});
test([1], [1].expand((x) => [x]));
test([1, 2, 3], [1, 2, 3].expand((x) => [x]));
test([], [1].expand((x) => []));
test([], [1, 2, 3].expand((x) => []));
test([2], [1, 2, 3].expand((x) => x == 2 ? [2] : []));
test([1, 1, 2, 2, 3, 3], [1, 2, 3].expand((x) => [x, x]));
test([1, 1, 2], [1, 2, 3].expand((x) => [x, x, x].skip(x)));
test([1], new MyList([1]).expand((x) => [x]));
test([1, 2, 3], new MyList([1, 2, 3]).expand((x) => [x]));
test([], new MyList([1]).expand((x) => []));
test([], new MyList([1, 2, 3]).expand((x) => []));
test([2], new MyList([1, 2, 3]).expand((x) => x == 2 ? [2] : []));
test([1, 1, 2, 2, 3, 3], new MyList([1, 2, 3]).expand((x) => [x, x]));
test([1, 1, 2], new MyList([1, 2, 3]).expand((x) => [x, x, x].skip(x)));
// if function throws, iteration is stopped.
Iterable iterable = [1, 2, 3].expand((x) {
if (x == 2) throw "FAIL";
return [x, x];
});
Iterator it = iterable.iterator;
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.throws(it.moveNext, (e) => e == "FAIL");
// After throwing, iteration is ended.
Expect.equals(null, it.current);
Expect.isFalse(it.moveNext());
}

View file

@ -0,0 +1,22 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(1, list1.first);
Expect.equals(4, list2.first);
Expect.throwsStateError(() => list3.first);
Expect.isTrue(set1.contains(set1.first));
Expect.throwsStateError(() => set2.first);
}

View file

@ -0,0 +1,43 @@
// Copyright (c) 2012, 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.
import 'package:expect/expect.dart';
main() {
List<int?> list1 = <int?>[1, 2, 3];
List<int?> list2 = const <int?>[4, 5];
List<String?> list3 = <String?>[];
Set<int?> set1 = new Set<int?>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(2, list1.firstWhere((x) => x!.isEven));
Expect.equals(1, list1.firstWhere((x) => x!.isOdd));
Expect.throwsStateError(() => list1.firstWhere((x) => x! > 3));
Expect.equals(null, list1.firstWhere((x) => x! > 3, orElse: () => null));
Expect.equals(499, list1.firstWhere((x) => x! > 3, orElse: () => 499));
Expect.equals(4, list2.firstWhere((x) => x!.isEven));
Expect.equals(5, list2.firstWhere((x) => x!.isOdd));
Expect.throwsStateError(() => list2.firstWhere((x) => x == 0));
Expect.equals(null, list2.firstWhere((x) => false, orElse: () => null));
Expect.equals(499, list2.firstWhere((x) => false, orElse: () => 499));
Expect.throwsStateError(() => list3.firstWhere((x) => x == 0));
Expect.throwsStateError(() => list3.firstWhere((x) => true));
Expect.equals(null, list3.firstWhere((x) => true, orElse: () => null));
Expect.equals("str", list3.firstWhere((x) => false, orElse: () => "str"));
Expect.equals(12, set1.firstWhere((x) => x!.isEven));
var odd = set1.firstWhere((x) => x!.isOdd);
Expect.isTrue(odd == 11 || odd == 13);
Expect.throwsStateError(() => set1.firstWhere((x) => false));
Expect.equals(null, set1.firstWhere((x) => false, orElse: () => null));
Expect.equals(499, set1.firstWhere((x) => false, orElse: () => 499));
Expect.throwsStateError(() => set2.firstWhere((x) => false));
Expect.throwsStateError(() => set2.firstWhere((x) => true));
Expect.equals(null, set2.firstWhere((x) => true, orElse: () => null));
Expect.equals(499, set2.firstWhere((x) => false, orElse: () => 499));
}

View file

@ -0,0 +1,206 @@
// Copyright (c) 2014, 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.
import "package:expect/expect.dart";
import 'dart:collection';
import 'dart:typed_data';
class MyList extends ListBase {
List list;
MyList(this.list);
get length => list.length;
set length(val) {
list.length = val;
}
operator [](index) => list[index];
operator []=(index, val) => list[index] = val;
}
Iterable id(Iterable x) => x;
main() {
for (dynamic iterable in [
const [1, 2, 3],
[1, 2, 3],
new List(3)
..[0] = 1
..[1] = 2
..[2] = 3,
{1: 1, 2: 2, 3: 3}.keys,
{1: 1, 2: 2, 3: 3}.values,
new Iterable.generate(3, (x) => x + 1),
new List.generate(3, (x) => x + 1),
[0, 1, 2, 3].where((x) => x > 0),
[0, 1, 2].map((x) => x + 1),
[
[1, 2],
[3]
].expand(id),
[3, 2, 1].reversed,
[0, 1, 2, 3].skip(1),
[1, 2, 3, 4].take(3),
new Uint8List(3)
..[0] = 1
..[1] = 2
..[2] = 3,
(new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3)
.keys,
(new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3)
.values,
(new SplayTreeMap()
..[1] = 0
..[2] = 0
..[3] = 0)
.keys,
(new SplayTreeMap()
..[0] = 1
..[1] = 2
..[2] = 3)
.values,
new HashSet()..add(1)..add(2)..add(3),
new LinkedHashSet()..add(1)..add(2)..add(3),
new SplayTreeSet()..add(1)..add(2)..add(3),
"\x01\x02\x03".codeUnits,
"\x01\x02\x03".runes,
new MyList([1, 2, 3]),
]) {
int callCount = 0;
var result = iterable.fold(0, (x, y) {
callCount++;
return x + y;
});
Expect.equals(6, result, "${iterable.runtimeType}");
Expect.equals(3, callCount);
}
// Empty iterables are allowed.
for (var iterable in [
const [],
[],
new List(0),
{}.keys,
{}.values,
new Iterable.generate(0, (x) => x + 1),
new List.generate(0, (x) => x + 1),
[0, 1, 2, 3].where((x) => false),
[].map((x) => x + 1),
[[], []].expand(id),
[].reversed,
[0, 1, 2, 3].skip(4),
[1, 2, 3, 4].take(0),
new Uint8List(0),
(new HashMap()).keys,
(new HashMap()).values,
(new SplayTreeMap()).keys,
(new SplayTreeMap()).values,
new HashSet(),
new LinkedHashSet(),
new SplayTreeSet(),
"".codeUnits,
"".runes,
new MyList([]),
]) {
Expect.equals(42, iterable.fold(42, (x, y) => throw "Unreachable"));
}
// Singleton iterables are calling reduce function.
for (dynamic iterable in [
const [1],
[1],
new List(1)..[0] = 1,
{1: 1}.keys,
{1: 1}.values,
new Iterable.generate(1, (x) => x + 1),
new List.generate(1, (x) => x + 1),
[0, 1, 2, 3].where((x) => x == 1),
[0].map((x) => x + 1),
[
[],
[1]
].expand(id),
[1].reversed,
[0, 1].skip(1),
[1, 2, 3, 4].take(1),
new Uint8List(1)..[0] = 1,
(new HashMap()..[1] = 0).keys,
(new HashMap()..[0] = 1).values,
(new SplayTreeMap()..[1] = 0).keys,
(new SplayTreeMap()..[0] = 1).values,
new HashSet()..add(1),
new LinkedHashSet()..add(1),
new SplayTreeSet()..add(1),
"\x01".codeUnits,
"\x01".runes,
new MyList([1]),
]) {
Expect.equals(43, iterable.fold(42, (x, y) => x + y));
}
// Concurrent modifications not allowed.
testModification(base, modify, transform) {
var iterable = transform(base);
Expect.throws(() {
iterable.fold(0, (x, y) {
modify(base);
return x + y;
});
}, (e) => e is ConcurrentModificationError);
}
void add4(collection) {
collection.add(4);
}
void addListOf4(collection) {
collection.add([4]);
}
void put4(map) {
map[4] = 4;
}
testModification([1, 2, 3], add4, id);
testModification(new HashSet()..add(1)..add(2)..add(3), add4, id);
testModification(new LinkedHashSet()..add(1)..add(2)..add(3), add4, id);
testModification(new SplayTreeSet()..add(1)..add(2)..add(3), add4, id);
testModification(new MyList([1, 2, 3]), add4, id);
testModification([0, 1, 2, 3], add4, (x) => x.where((int x) => x > 0));
testModification([0, 1, 2], add4, (x) => x.map((x) => x + 1));
testModification([
[1, 2],
[3]
], addListOf4, (x) => x.expand((List<int> x) => x));
testModification([3, 2, 1], add4, (x) => x.reversed);
testModification({1: 1, 2: 2, 3: 3}, put4, (x) => x.keys);
testModification({1: 1, 2: 2, 3: 3}, put4, (x) => x.values);
var hashMap = new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(hashMap, put4, (x) => x.keys);
hashMap = new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(hashMap, put4, (x) => x.values);
var splayMap = new SplayTreeMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(splayMap, put4, (x) => x.keys);
splayMap = new SplayTreeMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(splayMap, put4, (x) => x.values);
}

View file

@ -0,0 +1,102 @@
// Copyright (c) 2018, 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.
import "dart:collection" show Queue;
import "dart:typed_data" show Int32List;
import "package:expect/expect.dart";
// Tests behavior of result of an operation on a followedBy iterable.
test(List expects, Iterable iterable, [String? name]) {
try {
Expect.isFalse(iterable is List, "$name is! List");
Expect.isFalse(iterable is Set, "$name is! Set");
Expect.isFalse(iterable is Queue, "$name is! Queue");
if (expects.isNotEmpty) {
Expect.equals(expects.first, iterable.first, "$name: first");
Expect.equals(expects.last, iterable.last, "$name: last");
} else {
Expect.throwsStateError(() => iterable.first, "$name: first");
Expect.throwsStateError(() => iterable.last, "$name: last");
}
var it = iterable.iterator;
for (int index = 0; index < expects.length; index++) {
Expect.isTrue(it.moveNext(), "$name: has element $index");
var expect = expects[index];
Expect.equals(expect, it.current, "$name at $index");
Expect.equals(
expect, iterable.elementAt(index), "$name: elementAt($index)");
Expect.isTrue(iterable.contains(expect), "$name:contains $index");
}
Expect.isFalse(it.moveNext(),
"$name: extra element at ${expects.length}: ${it.current}");
} on Error {
print("Failed during: $name");
rethrow;
}
}
// Tests various operations on the a followedBy iterable.
tests(List<int> expects, Iterable<int> follow, [String? name]) {
int length = expects.length;
test(expects, follow, name);
for (int i = 0; i <= length; i++) {
test(expects.sublist(i), follow.skip(i), "$name.skip($i)");
}
for (int i = 0; i <= length; i++) {
test(expects.sublist(0, i), follow.take(i), "$name.take($i)");
}
for (int i = 0; i <= length; i++) {
for (int j = 0; j <= length - i; j++) {
test(expects.sublist(i, i + j), follow.skip(i).take(j),
"$name.skiptake($i,${i+j})");
test(expects.sublist(i, i + j), follow.take(i + j).skip(i),
"$name.takeskip($i,${i+j})");
}
}
}
// Tests various different types of iterables as first and second operand.
types(List<int> expects, List<int> first, List<int> second, String name) {
var conversions = <String, Iterable<int> Function(List<int>)>{
"const": toConst,
"list": toList,
"unmod": toUnmodifiable,
"set": toSet,
"queue": toQueue,
"eff-len-iter": toELIter,
"non-eff-iter": toNEIter,
"typed": toTyped,
"keys": toKeys,
"values": toValues,
};
conversions.forEach((n1, c1) {
conversions.forEach((n2, c2) {
tests(expects, c1(first).followedBy(c2(second)), "$name:$n1/$n2");
});
});
}
List<int> toConst(List<int> elements) => elements;
List<int> toList(List<int> elements) => elements.toList();
List<int> toUnmodifiable(List<int> elements) =>
new List<int>.unmodifiable(elements);
Set<int> toSet(List<int> elements) => elements.toSet();
Queue<int> toQueue(List<int> elements) => new Queue<int>.from(elements);
// Creates an efficient-length iterable.
Iterable<int> toELIter(List<int> elements) => elements.map<int>((x) => x);
// Creates a non-efficient-length iterable.
Iterable<int> toNEIter(List<int> elements) => elements.where((x) => true);
List<int> toTyped(List<int> elements) => new Int32List.fromList(elements);
Iterable<int> toKeys(List<int> elements) =>
new Map<int, int>.fromIterables(elements, elements).keys;
Iterable<int> toValues(List<int> elements) =>
new Map<int, int>.fromIterables(elements, elements).values;
main() {
types(<int>[], const <int>[], const <int>[], "0+0");
types(<int>[1, 2, 3, 4], const <int>[], const <int>[1, 2, 3, 4], "0+4");
types(<int>[1, 2, 3, 4], const <int>[1, 2], const <int>[3, 4], "2+2");
types(<int>[1, 2, 3, 4], const <int>[1, 2, 3, 4], const <int>[], "4+0");
}

View file

@ -0,0 +1,72 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
main() {
void test(expectedList, generatedIterable) {
Expect.equals(expectedList.length, generatedIterable.length);
Expect.listEquals(expectedList, generatedIterable.toList());
}
test([], new Iterable.generate(0));
test([0], new Iterable.generate(1));
test([0, 1, 2, 3, 4], new Iterable.generate(5));
test(["0", "1", "2", "3", "4"], new Iterable.generate(5, (x) => "$x"));
test([2, 3, 4, 5, 6], new Iterable.generate(7).skip(2));
test([0, 1, 2, 3, 4], new Iterable.generate(7).take(5));
test([], new Iterable.generate(5).skip(6));
test([], new Iterable.generate(5).take(0));
test([], new Iterable.generate(5).take(3).skip(3));
test([], new Iterable.generate(5).skip(6).take(0));
// Test types.
Iterable<int> it = new Iterable<int>.generate(5);
Expect.isTrue(it is Iterable<int>);
Expect.isTrue(it.iterator is Iterator<int>);
Expect.isTrue(it is! Iterable<String>);
Expect.isTrue(it.iterator is! Iterator<String>);
test([0, 1, 2, 3, 4], it);
Iterable<String> st = new Iterable<String>.generate(5, (x) => "$x");
Expect.isTrue(st is Iterable<String>);
Expect.isTrue(st.iterator is Iterator<String>);
Expect.isFalse(st is Iterable<int>);
Expect.isFalse(st.iterator is Iterator<int>);
test(["0", "1", "2", "3", "4"], st);
Expect.throws(() => new Iterable<String>.generate(5));
// Omitted generator function means `(int x) => x`, and the type parameters
// must then be compatible with `int`.
// Check that we catch invalid type parameters.
// Valid types:
Iterable<int> iter1 = new Iterable<int>.generate(5);
Expect.equals(2, iter1.elementAt(2));
Iterable<num> iter2 = new Iterable<num>.generate(5);
Expect.equals(2, iter2.elementAt(2));
Iterable<Object> iter3 = new Iterable<Object>.generate(5);
Expect.equals(2, iter3.elementAt(2));
Iterable<dynamic> iter4 = new Iterable<dynamic>.generate(5);
Expect.equals(2, iter4.elementAt(2));
// Invalid types:
Expect.throws(() => new Iterable<String>.generate(5));
Expect.throws(() => new Iterable<Null>.generate(5).elementAt(2)); //# 01: ok
Expect.throws(() => new Iterable<bool>.generate(5));
// Regression: https://github.com/dart-lang/sdk/issues/26358
var count = 0;
var iter = new Iterable.generate(5, (v) {
count++;
return v;
});
Expect.equals(0, count);
Expect.equals(2, iter.elementAt(2)); // Doesn't compute the earlier values.
Expect.equals(1, count);
Expect.equals(2, iter.skip(2).first); // Doesn't compute the skipped values.
Expect.equals(2, count);
}

View file

@ -0,0 +1,148 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
class IC {
int count = 0;
String toString() => "${count++}";
}
testJoin(String expect, Iterable iterable, [String? separator]) {
if (separator != null) {
Expect.equals(expect, iterable.join(separator));
} else {
Expect.equals(expect, iterable.join());
}
}
testCollections() {
testJoin("", [], ",");
testJoin("", [], "");
testJoin("", []);
testJoin("", new Set(), ",");
testJoin("", new Set(), "");
testJoin("", new Set());
testJoin("42", [42], ",");
testJoin("42", [42], "");
testJoin("42", [42]);
testJoin("42", new Set()..add(42), ",");
testJoin("42", new Set()..add(42), "");
testJoin("42", new Set()..add(42));
testJoin("a,b,c,d", ["a", "b", "c", "d"], ",");
testJoin("abcd", ["a", "b", "c", "d"], "");
testJoin("abcd", ["a", "b", "c", "d"]);
testJoin("null,b,c,d", [null, "b", "c", "d"], ",");
testJoin("1,2,3,4", [1, 2, 3, 4], ",");
var ic = new IC();
testJoin("0,1,2,3", [ic, ic, ic, ic], ",");
var set = new Set()..add(1)..add(2)..add(3);
var perm = new Set()
..add("123")
..add("132")
..add("213")
..add("231")
..add("312")
..add("321");
var setString = set.join();
Expect.isTrue(perm.contains(setString), "set: $setString");
void testArray(List<int> array) {
testJoin("1,3,5,7,9", array.where((i) => i.isOdd), ",");
testJoin("0,2,4,6,8,10,12,14,16,18", array.map((i) => i * 2), ",");
testJoin("5,6,7,8,9", array.skip(5), ",");
testJoin("5,6,7,8,9", array.skipWhile((i) => i < 5), ",");
testJoin("0,1,2,3,4", array.take(5), ",");
testJoin("0,1,2,3,4", array.takeWhile((i) => i < 5), ",");
}
testArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var fixedArray = new List<int>.filled(10, -1);
for (int i = 0; i < 10; i++) {
fixedArray[i] = i;
}
testArray(fixedArray);
testArray(const [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
testJoin("a,b,c,d", ["a", "b", "c", "d"].map((x) => x), ",");
testJoin("abcd", ["a", "b", "c", "d"].map((x) => x), "");
testJoin("abcd", ["a", "b", "c", "d"].map((x) => x));
testJoin("null,b,c,d", [null, "b", "c", "d"].map((x) => x), ",");
testJoin("1,2,3,4", [1, 2, 3, 4].map((x) => x), ",");
testJoin("4,5,6,7", [ic, ic, ic, ic].map((x) => x), ",");
}
void testStringVariants() {
// ASCII
testJoin("axbxcxd", ["a", "b", "c", "d"], "x");
testJoin("a\u2000b\u2000c\u2000d", ["a", "b", "c", "d"], "\u2000");
testJoin("abcd", ["a", "b", "c", "d"], "");
testJoin("abcd", ["a", "b", "c", "d"]);
// Non-ASCII
testJoin("axbxcx\u2000", ["a", "b", "c", "\u2000"], "x");
testJoin("a\u2000b\u2000c\u2000\u2000", ["a", "b", "c", "\u2000"], "\u2000");
testJoin("abc\u2000", ["a", "b", "c", "\u2000"], "");
testJoin("abc\u2000", ["a", "b", "c", "\u2000"]);
// Long-ASCII
testJoin("ax" * 255 + "a", new List.generate(256, (_) => "a"), "x");
testJoin("a" * 256, new List.generate(256, (_) => "a"));
// Long-Non-ASCII
testJoin("a\u2000" * 255 + "a", new List.generate(256, (_) => "a"), "\u2000");
testJoin("\u2000" * 256, new List.generate(256, (_) => "\u2000"));
testJoin(
"\u2000x" * 255 + "\u2000", new List.generate(256, (_) => "\u2000"), "x");
var o1 = new Stringable("x");
var o2 = new Stringable("\ufeff");
testJoin("xa" * 3 + "x", [o1, o1, o1, o1], "a");
testJoin("x" * 4, [o1, o1, o1, o1], "");
testJoin("x" * 4, [o1, o1, o1, o1]);
testJoin("\ufeffx" * 3 + "\ufeff", [o2, o2, o2, o2], "x");
testJoin("\ufeff" * 4, [o2, o2, o2, o2], "");
testJoin("\ufeff" * 4, [o2, o2, o2, o2]);
testJoin("a\u2000x\ufeff", ["a", "\u2000", o1, o2]);
testJoin("a\u2000\ufeffx", ["a", "\u2000", o2, o1]);
testJoin("ax\u2000\ufeff", ["a", o1, "\u2000", o2]);
testJoin("ax\ufeff\u2000", ["a", o1, o2, "\u2000"]);
testJoin("a\ufeffx\u2000", ["a", o2, o1, "\u2000"]);
testJoin("a\ufeff\u2000x", ["a", o2, "\u2000", o1]);
testJoin("\u2000ax\ufeff", ["\u2000", "a", o1, o2]);
testJoin("\u2000a\ufeffx", ["\u2000", "a", o2, o1]);
testJoin("xa\u2000\ufeff", [o1, "a", "\u2000", o2]);
testJoin("xa\ufeff\u2000", [o1, "a", o2, "\u2000"]);
testJoin("\ufeffax\u2000", [o2, "a", o1, "\u2000"]);
testJoin("\ufeffa\u2000x", [o2, "a", "\u2000", o1]);
testJoin("\u2000xa\ufeff", ["\u2000", o1, "a", o2]);
testJoin("\u2000\ufeffax", ["\u2000", o2, "a", o1]);
testJoin("x\u2000a\ufeff", [o1, "\u2000", "a", o2]);
testJoin("x\ufeffa\u2000", [o1, o2, "a", "\u2000"]);
testJoin("\ufeffxa\u2000", [o2, o1, "a", "\u2000"]);
testJoin("\ufeff\u2000ax", [o2, "\u2000", "a", o1]);
testJoin("\u2000x\ufeffa", ["\u2000", o1, o2, "a"]);
testJoin("\u2000\ufeffxa", ["\u2000", o2, o1, "a"]);
testJoin("x\u2000\ufeffa", [o1, "\u2000", o2, "a"]);
testJoin("x\ufeff\u2000a", [o1, o2, "\u2000", "a"]);
testJoin("\ufeffx\u2000a", [o2, o1, "\u2000", "a"]);
testJoin("\ufeff\u2000xa", [o2, "\u2000", o1, "a"]);
}
class Stringable {
final String value;
Stringable(this.value);
String toString() => value;
}
main() {
testCollections();
testStringVariants();
// TODO(lrn): test scalar lists.
}

View file

@ -0,0 +1,22 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(3, list1.last);
Expect.equals(5, list2.last);
Expect.throwsStateError(() => list3.last);
Expect.isTrue(set1.contains(set1.last));
Expect.throwsStateError(() => set2.last);
}

View file

@ -0,0 +1,43 @@
// Copyright (c) 2012, 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.
import 'package:expect/expect.dart';
main() {
List<int?> list1 = <int?>[1, 2, 3];
List<int?> list2 = const <int?>[4, 5, 6];
List<String?> list3 = <String?>[];
Set<int?> set1 = new Set<int?>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(2, list1.lastWhere((x) => x!.isEven));
Expect.equals(3, list1.lastWhere((x) => x!.isOdd));
Expect.throwsStateError(() => list1.lastWhere((x) => x! > 3));
Expect.equals(null, list1.lastWhere((x) => x! > 3, orElse: () => null));
Expect.equals(499, list1.lastWhere((x) => x! > 3, orElse: () => 499));
Expect.equals(6, list2.lastWhere((x) => x!.isEven));
Expect.equals(5, list2.lastWhere((x) => x!.isOdd));
Expect.throwsStateError(() => list2.lastWhere((x) => x == 0));
Expect.equals(null, list2.lastWhere((x) => false, orElse: () => null));
Expect.equals(499, list2.lastWhere((x) => false, orElse: () => 499));
Expect.throwsStateError(() => list3.lastWhere((x) => x == 0));
Expect.throwsStateError(() => list3.lastWhere((x) => true));
Expect.equals(null, list3.lastWhere((x) => true, orElse: () => null));
Expect.equals("str", list3.lastWhere((x) => false, orElse: () => "str"));
Expect.equals(12, set1.lastWhere((x) => x!.isEven));
var odd = set1.lastWhere((x) => x!.isOdd);
Expect.isTrue(odd == 11 || odd == 13);
Expect.throwsStateError(() => set1.lastWhere((x) => false));
Expect.equals(null, set1.lastWhere((x) => false, orElse: () => null));
Expect.equals(499, set1.lastWhere((x) => false, orElse: () => 499));
Expect.throwsStateError(() => set2.lastWhere((x) => false));
Expect.throwsStateError(() => set2.lastWhere((x) => true));
Expect.equals(null, set2.lastWhere((x) => true, orElse: () => null));
Expect.equals(499, set2.lastWhere((x) => false, orElse: () => 499));
}

View file

@ -0,0 +1,44 @@
// Copyright (c) 2012, 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.
import "dart:collection";
import "package:expect/expect.dart";
class A extends IterableBase {
int count;
A(this.count);
Iterator get iterator {
return new AIterator(count);
}
}
class AIterator implements Iterator {
int _count;
int? _current;
AIterator(this._count);
bool moveNext() {
if (_count > 0) {
_current = _count;
_count--;
return true;
}
_current = null;
return false;
}
get current => _current;
}
main() {
var a = new A(10);
Expect.equals(10, a.length);
a = new A(0);
Expect.equals(0, a.length);
a = new A(5);
Expect.equals(5, a.map((e) => e + 1).length);
Expect.equals(3, a.where((e) => e >= 3).length);
}

View file

@ -0,0 +1,50 @@
// Copyright (c) 2013, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1.addAll([11, 12, 13]);
Set set2 = new Set();
Iterable mapped = list1.map((x) => x + 1);
Expect.listEquals([2, 3, 4], mapped.toList());
mapped = mapped.map((x) => x + 1);
Expect.listEquals([3, 4, 5], mapped.toList());
mapped = list2.map((x) => x + 1);
Expect.listEquals([5, 6], mapped.toList());
mapped = mapped.map((x) => x + 1);
Expect.listEquals([6, 7], mapped.toList());
mapped = list3.map((x) => x + 1); //# 01: compile-time error
Expect.listEquals([], mapped.toList()); //# 01: continued
mapped = mapped.map((x) => x + 1); //# 01: continued
Expect.listEquals([], mapped.toList()); //# 01: continued
var expected = new Set<int>()..addAll([12, 13, 14]);
mapped = set1.map((x) => x + 1);
Expect.isFalse(mapped is List);
Expect.setEquals(expected, mapped.toSet());
expected = new Set<int>()..addAll([13, 14, 15]);
mapped = mapped.map((x) => x + 1);
Expect.isFalse(mapped is List);
Expect.setEquals(expected, mapped.toSet());
mapped = set2.map((x) => x + 1);
Expect.isFalse(mapped is List);
Expect.listEquals([], mapped.toList());
mapped = mapped.map((x) => x + 1);
Expect.isFalse(mapped is List);
Expect.listEquals([], mapped.toList());
}

View file

@ -0,0 +1,210 @@
// Copyright (c) 2014, 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.
import "package:expect/expect.dart";
import 'dart:collection';
import 'dart:typed_data';
class MyList extends ListBase {
List list;
MyList(this.list);
get length => list.length;
set length(val) {
list.length = val;
}
operator [](index) => list[index];
operator []=(index, val) => list[index] = val;
}
Iterable id(Iterable x) => x;
main() {
// Test functionality.
for (dynamic iterable in [
const [1, 2, 3],
[1, 2, 3],
new List(3)
..[0] = 1
..[1] = 2
..[2] = 3,
{1: 1, 2: 2, 3: 3}.keys,
{1: 1, 2: 2, 3: 3}.values,
new Iterable.generate(3, (x) => x + 1),
new List.generate(3, (x) => x + 1),
[0, 1, 2, 3].where((x) => x > 0),
[0, 1, 2].map((x) => x + 1),
[
[1, 2],
[3]
].expand(id),
[3, 2, 1].reversed,
[0, 1, 2, 3].skip(1),
[1, 2, 3, 4].take(3),
new Uint8List(3)
..[0] = 1
..[1] = 2
..[2] = 3,
(new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3)
.keys,
(new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3)
.values,
(new SplayTreeMap()
..[1] = 0
..[2] = 0
..[3] = 0)
.keys,
(new SplayTreeMap()
..[0] = 1
..[1] = 2
..[2] = 3)
.values,
new HashSet()..add(1)..add(2)..add(3),
new LinkedHashSet()..add(1)..add(2)..add(3),
new SplayTreeSet()..add(1)..add(2)..add(3),
"\x01\x02\x03".codeUnits,
"\x01\x02\x03".runes,
new MyList([1, 2, 3]),
]) {
int callCount = 0;
var result = iterable.reduce((x, y) {
callCount++;
// Return type of reduce() callback should match element type.
return (x + y) as int;
});
Expect.equals(6, result, "${iterable.runtimeType}");
Expect.equals(2, callCount);
}
// Empty iterables not allowed.
for (var iterable in [
const [],
[],
new List(0),
{}.keys,
{}.values,
new Iterable.generate(0, (x) => x + 1),
new List.generate(0, (x) => x + 1),
[0, 1, 2, 3].where((x) => false),
[].map((x) => x + 1),
[[], []].expand(id),
[].reversed,
[0, 1, 2, 3].skip(4),
[1, 2, 3, 4].take(0),
new Uint8List(0),
(new HashMap()).keys,
(new HashMap()).values,
(new SplayTreeMap()).keys,
(new SplayTreeMap()).values,
new HashSet(),
new LinkedHashSet(),
new SplayTreeSet(),
"".codeUnits,
"".runes,
new MyList([]),
]) {
Expect
.throwsStateError(() => iterable.reduce((x, y) => throw "Unreachable"));
}
// Singleton iterables not calling reduce function.
for (dynamic iterable in [
const [1],
[1],
new List(1)..[0] = 1,
{1: 1}.keys,
{1: 1}.values,
new Iterable.generate(1, (x) => x + 1),
new List.generate(1, (x) => x + 1),
[0, 1, 2, 3].where((x) => x == 1),
[0].map((x) => x + 1),
[
[],
[1]
].expand(id),
[1].reversed,
[0, 1].skip(1),
[1, 2, 3, 4].take(1),
new Uint8List(1)..[0] = 1,
(new HashMap()..[1] = 0).keys,
(new HashMap()..[0] = 1).values,
(new SplayTreeMap()..[1] = 0).keys,
(new SplayTreeMap()..[0] = 1).values,
new HashSet()..add(1),
new LinkedHashSet()..add(1),
new SplayTreeSet()..add(1),
"\x01".codeUnits,
"\x01".runes,
new MyList([1]),
]) {
Expect.equals(1, iterable.reduce((x, y) => throw "Unreachable"));
}
// Concurrent modifications not allowed.
testModification(base, modify, transform) {
var iterable = transform(base);
Expect.throws(() {
iterable.reduce((x, y) {
modify(base);
// Return type of reduce() callback should match element type.
return (x + y) as int;
});
}, (e) => e is ConcurrentModificationError);
}
void add4(collection) {
collection.add(4);
}
void addListOf4(collection) {
collection.add([4]);
}
void put4(map) {
map[4] = 4;
}
testModification([1, 2, 3], add4, id);
testModification(new HashSet()..add(1)..add(2)..add(3), add4, id);
testModification(new LinkedHashSet()..add(1)..add(2)..add(3), add4, id);
testModification(new SplayTreeSet()..add(1)..add(2)..add(3), add4, id);
testModification(new MyList([1, 2, 3]), add4, id);
testModification([0, 1, 2, 3], add4, (x) => x.where((int x) => x > 0));
testModification([0, 1, 2], add4, (x) => x.map((x) => x + 1));
testModification([
[1, 2],
[3]
], addListOf4, (x) => x.expand((List<int> x) => x));
testModification([3, 2, 1], add4, (x) => x.reversed);
testModification({1: 1, 2: 2, 3: 3}, put4, (x) => x.keys);
testModification({1: 1, 2: 2, 3: 3}, put4, (x) => x.values);
var hashMap = new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(hashMap, put4, (x) => x.keys);
hashMap = new HashMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(hashMap, put4, (x) => x.values);
var splayMap = new SplayTreeMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(splayMap, put4, (x) => x.keys);
splayMap = new SplayTreeMap()
..[1] = 1
..[2] = 2
..[3] = 3;
testModification(splayMap, put4, (x) => x.values);
}

View file

@ -0,0 +1,90 @@
// Copyright (c) 2013, 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.
// Regression test for dart2js where [List.addAll] was not typed
// correctly.
import "package:expect/expect.dart";
import 'dart:collection';
import 'dart:typed_data';
testIntIterable(iterable) {
Expect.isTrue(iterable is Iterable<int>, "${iterable.runtimeType}");
Expect.isFalse(iterable is Iterable<String>, "${iterable.runtimeType}");
}
void testIterable(Iterable<int> iterable, [int depth = 3]) {
testIntIterable(iterable);
if (depth > 0) {
testIterable(iterable.where((x) => true), depth - 1);
testIterable(iterable.skip(1), depth - 1);
testIterable(iterable.take(1), depth - 1);
testIterable(iterable.skipWhile((x) => false), depth - 1);
testIterable(iterable.takeWhile((x) => true), depth - 1);
testList(iterable.toList(growable: true), depth - 1);
testList(iterable.toList(growable: false), depth - 1);
testIterable(iterable.toSet(), depth - 1);
}
}
void testList(List<int> list, [int depth = 3]) {
testIterable(list, depth);
if (depth > 0) {
testIterable(list.getRange(0, list.length), depth - 1);
testIterable(list.reversed, depth - 1);
testMap(list.asMap(), depth - 1);
}
}
void testMap(Map<int, int> map, [int depth = 3]) {
Expect.isTrue(map is Map<int, int>);
Expect.isFalse(map is Map<int, String>);
Expect.isFalse(map is Map<String, int>);
if (depth > 0) {
testIterable(map.keys, depth - 1);
testIterable(map.values, depth - 1);
}
}
main() {
// Empty lists.
testList(<int>[]);
testList(new List<int>.empty());
testList(new List<int>());
testList(const <int>[]);
testList(new List<int>.generate(0, (x) => x + 1));
// Singleton lists.
testList(<int>[1]);
testList(new List<int>.filled(1, 1));
testList(new List<int>()..add(1));
testList(const <int>[1]);
testList(new List<int>.generate(1, (x) => x + 1));
// Typed lists.
testList(new Uint8List(1)..[0] = 1); // //# 01: ok
testList(new Int8List(1)..[0] = 1); // //# 01: continued
testList(new Uint16List(1)..[0] = 1); // //# 01: continued
testList(new Int16List(1)..[0] = 1); // //# 01: continued
testList(new Uint32List(1)..[0] = 1); // //# 01: continued
testList(new Int32List(1)..[0] = 1); // //# 01: continued
testList(new Uint64List(1)..[0] = 1); // //# 02: ok
testList(new Int64List(1)..[0] = 1); // //# 02: continued
testIterable(new Set<int>()..add(1));
testIterable(new HashSet<int>()..add(1));
testIterable(new LinkedHashSet<int>()..add(1));
testIterable(new SplayTreeSet<int>()..add(1));
testIterable(new Queue<int>()..add(1));
testIterable(new DoubleLinkedQueue<int>()..add(1));
testIterable(new ListQueue<int>()..add(1));
testMap(new Map<int, int>()..[1] = 1);
testMap(new HashMap<int, int>()..[1] = 1);
testMap(new LinkedHashMap<int, int>()..[1] = 1);
testMap(new SplayTreeMap<int, int>()..[1] = 1);
testMap(<int, int>{1: 1});
testMap(const <int, int>{1: 1});
}

View file

@ -0,0 +1,31 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1a = <int>[1];
List<int> list1b = <int>[1, 2, 3];
List<int> list1c = <int>[];
List<int> list2a = const <int>[5];
List<int> list2b = const <int>[4, 5];
List<int> list2c = const <int>[];
Set<int> set1 = new Set<int>();
set1..add(22);
Set set2 = new Set();
set2..add(11)..add(12)..add(13);
Set set3 = new Set();
Expect.equals(1, list1a.single);
Expect.throwsStateError(() => list1b.single);
Expect.throwsStateError(() => list1c.single);
Expect.equals(5, list2a.single);
Expect.throwsStateError(() => list2b.single);
Expect.throwsStateError(() => list2c.single);
Expect.equals(22, set1.single);
Expect.throwsStateError(() => set2.single);
Expect.throwsStateError(() => set3.single);
}

View file

@ -0,0 +1,30 @@
// Copyright (c) 2012, 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.
import 'package:expect/expect.dart';
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5, 6];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Expect.equals(2, list1.singleWhere((x) => x.isEven));
Expect.equals(3, list1.singleWhere((x) => x == 3));
Expect.throwsStateError(() => list1.singleWhere((x) => x.isOdd));
Expect.equals(6, list2.singleWhere((x) => x == 6));
Expect.equals(5, list2.singleWhere((x) => x.isOdd));
Expect.throwsStateError(() => list2.singleWhere((x) => x.isEven));
Expect.throwsStateError(() => list3.singleWhere((x) => x == 0));
Expect.equals(12, set1.singleWhere((x) => x.isEven));
Expect.equals(11, set1.singleWhere((x) => x == 11));
Expect.throwsStateError(() => set1.singleWhere((x) => x.isOdd));
Expect.throwsStateError(() => set2.singleWhere((x) => true));
}

View file

@ -0,0 +1,257 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Iterable<int> skip0 = list1.skip(0);
Expect.isTrue(skip0 is! List);
Iterator<int> it = skip0.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skip1 = list1.skip(1);
Expect.isTrue(skip1 is! List);
Expect.isTrue(skip1.skip(2).skip(1) is! List);
it = skip1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skip2 = list1.skip(2);
Expect.isTrue(skip2 is! List);
Expect.isTrue(skip2.skip(2).skip(1) is! List);
it = skip2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skip3 = list1.skip(3);
Expect.isTrue(skip3 is! List);
Expect.isTrue(skip3.skip(2).skip(1) is! List);
it = skip3.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skip4 = list1.skip(4);
Expect.isTrue(skip4 is! List);
Expect.isTrue(skip4.skip(2).skip(1) is! List);
it = skip4.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip0 = list1.skip(0);
skip1 = skip0.skip(1);
skip2 = skip1.skip(1);
skip3 = skip2.skip(1);
skip4 = skip3.skip(1);
it = skip0.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = skip1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = skip2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = skip3.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = skip4.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip0 = list2.skip(0);
Expect.isTrue(skip0 is! List);
Expect.isTrue(skip0.skip(2).skip(1) is! List);
it = skip0.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip1 = list2.skip(1);
Expect.isTrue(skip1 is! List);
Expect.isTrue(skip1.skip(2).skip(1) is! List);
it = skip1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip2 = list2.skip(2);
Expect.isTrue(skip2 is! List);
Expect.isTrue(skip2.skip(2).skip(1) is! List);
it = skip2.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip3 = list2.skip(3);
Expect.isTrue(skip3 is! List);
Expect.isTrue(skip3.skip(2).skip(1) is! List);
it = skip3.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<String> skip02 = list3.skip(0);
Expect.isTrue(skip02 is! List);
Expect.isTrue(skip02.skip(2).skip(1) is! List);
Iterator<String> it2 = skip02.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
Iterable<String> skip12 = list3.skip(1);
Expect.isTrue(skip12 is! List);
Expect.isTrue(skip12.skip(2).skip(1) is! List);
it2 = skip12.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
skip0 = set1.skip(0);
List<int> copied = skip0.toList();
Expect.equals(3, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(set1.contains(copied[2]));
Expect.isTrue(copied[0] != copied[1]);
Expect.isTrue(copied[0] != copied[2]);
Expect.isTrue(copied[1] != copied[2]);
it = skip0.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip1 = set1.skip(1);
copied = skip1.toList();
Expect.equals(2, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(copied[0] != copied[1]);
it = skip1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip2 = set1.skip(2);
copied = skip2.toList();
Expect.equals(1, copied.length);
Expect.isTrue(set1.contains(copied[0]));
it = skip2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip3 = set1.skip(3);
it = skip3.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skip4 = set1.skip(4);
it = skip4.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
var dynamicSkip0 = set2.skip(0);
var dynamicIt = dynamicSkip0.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
var dynamicSkip1 = set2.skip(1);
dynamicIt = dynamicSkip1.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
testSkipTake(Iterable input, int skip, int take) {
List expected = [];
Iterator iter = input.iterator;
for (int i = 0; i < skip; i++) iter.moveNext();
for (int i = 0; i < take; i++) {
if (!iter.moveNext()) break;
expected.add(iter.current);
}
Expect.listEquals(expected, input.skip(skip).take(take).toList());
}
List longList = [1, 4, 5, 3, 8, 11, 12, 6, 9, 10, 13, 7, 2, 14, 15];
Set bigSet = longList.toSet();
for (Iterable collection in [longList, longList.reversed, bigSet]) {
testSkipTake(collection, 0, 0);
testSkipTake(collection, 0, 5);
testSkipTake(collection, 0, 15);
testSkipTake(collection, 0, 25);
testSkipTake(collection, 5, 0);
testSkipTake(collection, 5, 5);
testSkipTake(collection, 5, 10);
testSkipTake(collection, 5, 20);
testSkipTake(collection, 15, 0);
testSkipTake(collection, 15, 5);
testSkipTake(collection, 20, 0);
testSkipTake(collection, 20, 5);
Expect.throwsRangeError(() => longList.skip(-1));
}
}

View file

@ -0,0 +1,146 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Iterable<int> skipWhileTrue = list1.skipWhile((x) => true);
Iterator<int> it = skipWhileTrue.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skipWhileOdd = list1.skipWhile((x) => x.isOdd);
it = skipWhileOdd.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skipWhileLessThan3 = list1.skipWhile((x) => x < 3);
it = skipWhileLessThan3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skipWhileFalse = list1.skipWhile((x) => false);
it = skipWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> skipWhileEven = list1.skipWhile((x) => x.isEven);
it = skipWhileEven.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skipWhileTrue = list2.skipWhile((x) => true);
it = skipWhileTrue.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skipWhileEven = list2.skipWhile((x) => x.isEven);
it = skipWhileEven.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skipWhileOdd = list2.skipWhile((x) => x.isOdd);
it = skipWhileOdd.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skipWhileFalse = list2.skipWhile((x) => false);
it = skipWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<String> skipWhileFalse2 = list3.skipWhile((x) => false);
Iterator<String> it2 = skipWhileFalse2.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
Iterable<String> skipWhileTrue2 = list3.skipWhile((x) => true);
it2 = skipWhileTrue2.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
skipWhileTrue = set1.skipWhile((x) => true);
it = skipWhileTrue.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
skipWhileFalse = set1.skipWhile((x) => false);
List<int> copied = skipWhileFalse.toList();
Expect.equals(3, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(copied[0] != copied[1]);
Expect.isTrue(copied[0] != copied[2]);
Expect.isTrue(copied[1] != copied[2]);
it = skipWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
var dynamicSkipWhileTrue = set2.skipWhile((x) => true);
var dynamicIt = dynamicSkipWhileTrue.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
var dynamicSkipWhileFalse = set2.skipWhile((x) => false);
dynamicIt = dynamicSkipWhileFalse.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
}

View file

@ -0,0 +1,227 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Iterable<int> take0 = list1.take(0);
Iterator<int> it = take0.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> take1 = list1.take(1);
it = take1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> take2 = list1.take(2);
it = take2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> take3 = list1.take(3);
it = take3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> take4 = list1.take(4);
it = take4.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take4 = list1.take(4);
take3 = take4.take(3);
take2 = take3.take(2);
take1 = take2.take(1);
take0 = take1.take(0);
it = take0.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = take1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = take2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = take3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
it = take4.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take0 = list2.take(0);
it = take0.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take1 = list2.take(1);
it = take1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take2 = list2.take(2);
it = take2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take3 = list2.take(3);
it = take3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<String> take02 = list3.take(0);
Iterator<String> it2 = take02.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
Iterable<String> take12 = list3.take(1);
it2 = take12.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
take0 = set1.take(0);
it = take0.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take1 = set1.take(1);
List<int> copied = take1.toList();
Expect.equals(1, copied.length);
Expect.isTrue(set1.contains(copied[0]));
it = take1.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take2 = set1.take(2);
copied = take2.toList();
Expect.equals(2, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(copied[0] != copied[1]);
it = take2.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
take3 = set1.take(3);
copied = take3.toList();
Expect.equals(3, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(set1.contains(copied[2]));
Expect.isTrue(copied[0] != copied[1]);
Expect.isTrue(copied[0] != copied[2]);
Expect.isTrue(copied[1] != copied[2]);
it = take3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isNotNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
var dynamicTake0 = set2.take(0);
var dynamicIt = dynamicTake0.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
var dynamicTake1 = set2.take(1);
dynamicIt = dynamicTake1.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
Expect.throwsRangeError(() => list1.skip(-1));
Expect.throwsRangeError(() => list2.skip(-1));
Expect.throwsRangeError(() => list3.skip(-1));
Expect.throwsRangeError(() => set1.skip(-1));
Expect.throwsRangeError(() => set2.skip(-1));
Expect.throwsRangeError(() => list1.map((x) => x).skip(-1));
Expect.throwsRangeError(() => list2.map((x) => x).skip(-1));
Expect.throwsRangeError(() => list3.map((x) => x).skip(-1));
Expect.throwsRangeError(() => set1.map((x) => x).skip(-1));
Expect.throwsRangeError(() => set2.map((x) => x).skip(-1));
}

View file

@ -0,0 +1,130 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 5];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set set2 = new Set();
Iterable<int> takeWhileFalse = list1.takeWhile((x) => false);
Iterator<int> it = takeWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> takeWhileOdd = list1.takeWhile((x) => x.isOdd);
it = takeWhileOdd.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> takeWhileLessThan3 = list1.takeWhile((x) => x < 3);
it = takeWhileLessThan3.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> takeEverything = list1.takeWhile((x) => true);
it = takeEverything.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(1, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(2, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(3, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<int> takeWhileEven = list1.takeWhile((x) => x.isEven);
it = takeWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
takeWhileFalse = list2.takeWhile((x) => false);
it = takeWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
takeWhileEven = list2.takeWhile((x) => x.isEven);
it = takeWhileEven.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
takeEverything = list2.takeWhile((x) => true);
it = takeEverything.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.equals(4, it.current);
Expect.isTrue(it.moveNext());
Expect.equals(5, it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
Iterable<String> takeWhileFalse2 = list3.takeWhile((x) => false);
Iterator<String> it2 = takeWhileFalse2.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
Iterable<String> takeEverything2 = list3.takeWhile((x) => true);
it2 = takeEverything2.iterator;
Expect.isNull(it2.current);
Expect.isFalse(it2.moveNext());
Expect.isNull(it2.current);
takeWhileFalse = set1.takeWhile((x) => false);
it = takeWhileFalse.iterator;
Expect.isNull(it.current);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
takeEverything = set1.takeWhile((x) => true);
List<int> copied = takeEverything.toList();
Expect.equals(3, copied.length);
Expect.isTrue(set1.contains(copied[0]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(set1.contains(copied[1]));
Expect.isTrue(copied[0] != copied[1]);
Expect.isTrue(copied[0] != copied[2]);
Expect.isTrue(copied[1] != copied[2]);
it = takeEverything.iterator;
Expect.isNull(it.current);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isTrue(it.moveNext());
Expect.isTrue(it.current != null);
Expect.isFalse(it.moveNext());
Expect.isNull(it.current);
var dynamicTakeWhileFalse = set2.takeWhile((x) => false);
var dynamicIt = dynamicTakeWhileFalse.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
var dynamicTakeEverything = set2.takeWhile((x) => true);
dynamicIt = dynamicTakeEverything.iterator;
Expect.isNull(dynamicIt.current);
Expect.isFalse(dynamicIt.moveNext());
Expect.isNull(dynamicIt.current);
}

View file

@ -0,0 +1,18 @@
// Copyright (c) 2013, 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.
// Regression test for dart2js where [List.addAll] was not typed
// correctly.
import "package:expect/expect.dart";
import 'dart:collection';
class MyIterable extends IterableBase {
get iterator => [].iterator;
}
main() {
Expect.isTrue(([]..addAll(new MyIterable())).isEmpty);
}

View file

@ -0,0 +1,73 @@
// Copyright (c) 2012, 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.
import "dart:collection" show Queue;
import "dart:typed_data" show Uint8List, Float32List;
import "package:expect/expect.dart";
main() {
// testIterable takes an iterable and a list expected to be equal to
// the iterable's toList result, including the type parameter of the list.
testIterable(<dynamic>[], <dynamic>[]);
testIterable(<int>[], <int>[]);
testIterable(<String>[], <String>[]);
testIterable([1, 2, 3], [1, 2, 3]);
testIterable(<int>[1, 2, 3], <int>[1, 2, 3]);
testIterable(const [1, 2], [1, 2]);
testIterable(const <int>[1, 2], <int>[1, 2]);
testIterable(<dynamic, dynamic>{"x": 1, "y": 1}.keys, <dynamic>["x", "y"]);
testIterable(<String, int>{"x": 1, "y": 1}.keys, <String>["x", "y"]);
testIterable(<dynamic, dynamic>{"x": 2, "y": 3}.values, <dynamic>[2, 3]);
testIterable(<String, int>{"x": 2, "y": 3}.values, <int>[2, 3]);
testIterable(new Iterable.generate(3), [0, 1, 2]);
testIterable(new Iterable<int>.generate(3), <int>[0, 1, 2]);
testIterable(
new Iterable<String>.generate(3, (x) => "$x"), <String>["0", "1", "2"]);
testIterable(new Set.from([1, 2, 3]), [1, 2, 3]);
testIterable(new Set<int>.from([1, 2, 3]), <int>[1, 2, 3]);
testIterable(new Queue.from([1, 2, 3]), [1, 2, 3]);
testIterable(new Queue<int>.from(<int>[1, 2, 3]), <int>[1, 2, 3]);
testIterable(new Uint8List.fromList(<int>[1, 2, 3]), // //# 01: ok
<int>[1, 2, 3]); // //# 01: continued
testIterable(new Float32List.fromList([1.0, 2.0, 3.0]), // //# 01: continued
<double>[1.0, 2.0, 3.0]); // //# 01: continued
testIterable("abc".codeUnits, <int>[97, 98, 99]); // //# 01: continued
testIterable("abc".runes, <int>[97, 98, 99]);
}
testIterable(Iterable iterable, List expected, [int depth = 0]) {
print(" " * depth + "${iterable.runtimeType} vs ${expected.runtimeType}");
test(iterable, expected);
test(iterable, expected, growable: true);
test(iterable, expected, growable: false);
if (depth < 2) {
depth++;
testIterable(iterable.map((x) => x), new List.from(expected), depth);
testIterable(iterable.where((x) => true), expected, depth);
testIterable(iterable.expand((x) => [x]), new List.from(expected), depth);
testIterable(iterable.map((x) => x), new List.from(expected), depth);
testIterable(iterable.skipWhile((x) => false), expected, depth);
testIterable(iterable.takeWhile((x) => true), expected, depth);
testIterable(iterable.skip(0), expected, depth);
testIterable(iterable.take(expected.length * 2), expected, depth);
testIterable(iterable.toSet(), expected, depth);
}
}
test(Iterable iterable, List expected, {bool growable: true}) {
var list = iterable.toList(growable: growable);
Expect.listEquals(expected, list);
Expect.equals(expected is List<int>, list is List<int>, "int");
Expect.equals(expected is List<double>, list is List<double>, "double");
Expect.equals(expected is List<String>, list is List<String>, "str");
if (growable) {
int length = list.length;
list.add(null);
Expect.equals(length + 1, list.length);
} else {
Expect.throws(() {
list.add(null);
});
}
}

View file

@ -0,0 +1,54 @@
// Copyright (c) 2012, 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.
import "package:expect/expect.dart";
main() {
List<int> list1 = <int>[1, 2, 3];
List<int> list2 = const <int>[4, 4];
List<String> list3 = <String>[];
Set<int> set1 = new Set<int>();
set1..add(11)..add(12)..add(13);
Set<String> set2 = new Set<String>();
set2..add("foo")..add("bar")..add("toto");
Set set3 = new Set();
var setCopy = list1.toSet();
Expect.equals(3, setCopy.length);
Expect.isTrue(setCopy.contains(1));
Expect.isTrue(setCopy.contains(2));
Expect.isTrue(setCopy.contains(3));
Expect.isTrue(setCopy is Set<int>);
Expect.isFalse(setCopy is Set<String>);
setCopy = list2.toSet();
Expect.equals(1, setCopy.length);
Expect.isTrue(setCopy.contains(4));
Expect.isTrue(setCopy is Set<int>);
Expect.isFalse(setCopy is Set<String>);
var setStrCopy = list3.toSet();
Expect.isTrue(setStrCopy.isEmpty);
Expect.isTrue(setStrCopy is Set<String>);
Expect.isFalse(setStrCopy is Set<int>);
setCopy = set1.toSet();
Expect.setEquals(set1, setCopy);
Expect.isTrue(setCopy is Set<int>);
Expect.isFalse(setCopy is Set<String>);
Expect.isFalse(identical(setCopy, set1));
setStrCopy = set2.toSet();
Expect.setEquals(set2, setStrCopy);
Expect.isTrue(setStrCopy is Set<String>);
Expect.isFalse(setStrCopy is Set<int>);
Expect.isFalse(identical(setStrCopy, set2));
var set3Copy = set3.toSet();
Expect.setEquals(set3, set3Copy);
Expect.isTrue(set3Copy is Set);
Expect.isFalse(set3Copy is Set<String>);
Expect.isFalse(set3Copy is Set<int>);
Expect.isFalse(identical(set3Copy, set3));
}

View file

@ -0,0 +1,106 @@
// Copyright (c) 2013, 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.
// Test the IterableBase/IterableMixin toString method.
import "package:expect/expect.dart";
import "dart:collection";
String mkIt(int len, [func]) {
var list;
if (func == null) {
list = new List.generate(len, (x) => x);
} else {
list = new List.generate(len, func);
}
return new MyIterable(list).toString();
}
class MyIterable extends IterableBase {
final Iterable _base;
MyIterable(this._base);
Iterator get iterator => _base.iterator;
}
void main() {
Expect.equals("()", mkIt(0));
Expect.equals("(0)", mkIt(1));
Expect.equals("(0, 1)", mkIt(2));
Expect.equals("(0, 1, 2, 3, 4, 5, 6, 7, 8)", mkIt(9));
// Builds string up to 60 characters, then finishes with last two
// elements.
Expect.equals(
//0123456789012345678901234567890123456789 - 40 characters
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, 14, 15, 16, 17, 18, ..., 98, 99)",
mkIt(100));
Expect.equals(
//0123456789012345678901234567890123456789
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, 14, 15, 16, 17, 18)",
mkIt(19));
Expect.equals(
//0123456789012345678901234567890123456789
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, 14, 15, 16, 17, 18, 19)",
mkIt(20));
Expect.equals(
//0123456789012345678901234567890123456789
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, 14, 15, 16, 17, 18, 19, 20)",
mkIt(21));
// Don't show last two elements if more than 100 elements total
// (can't be 100 elements in 80 characters including commas).
Expect.equals(
//0123456789012345678901234567890123456789
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, 14, 15, 16, 17, 18, 19, 20, ...)",
mkIt(101));
// If last two elements bring total over 80 characters, drop some of
// the previous ones as well.
Expect.equals(
//0123456789012345678901234567890123456789
"(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1"
"2, 13, ..., 18, xxxxxxxxxxxxxxxxxxxx)",
mkIt(20, (x) => x == 19 ? "xxxxxxxxxxxxxxxxxxxx" : "$x"));
// Never drop the first three or the last two.
Expect.equals(
//0123456789012345678901234567890123456789
"(xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxxx, x"
"xxxxxxxxxxxxxxxx, ..., 18, xxxxxxxxxxxxx"
"xxxx)",
mkIt(20, (x) => (x < 3 || x == 19) ? "xxxxxxxxxxxxxxxxx" : "$x"));
// Never drop the first three or the last two.
Expect.equals(
//0123456789012345678901234567890123456789
"(xxxxxxxxxxxxxxxxx, xxxxxxxxxxxxxxxxx, x"
"xxxxxxxxxxxxxxxx, ..., xxxxxxxxxxxxxxxxx"
", 19)",
mkIt(20, (x) => (x < 3 || x == 18) ? "xxxxxxxxxxxxxxxxx" : "$x"));
// If the first three are very long, always include them anyway.
Expect.equals(
//0123456789012345678901234567890123456789
"(xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,"
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,"
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,"
" ..., 98, 99)",
mkIt(100,
(x) => (x < 3) ? "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" : "$x"));
Expect.equals(
//0123456789012345678901234567890123456789
"(, , , , , , , , , , , , , , , , , , , ,"
" , , , , , , , , , , , , , , , ..., , )",
mkIt(100, (_) => ""));
}

View file

@ -0,0 +1,105 @@
// Copyright (c) 2018, 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.
import "dart:collection" show Queue;
import "dart:typed_data" show Int32List;
import "package:expect/expect.dart";
// Tests behavior of result of an operation on a followedBy iterable.
test(List expects, Iterable iterable, [String? name]) {
try {
Expect.isFalse(iterable is List, "$name is! List");
Expect.isFalse(iterable is Set, "$name is! Set");
Expect.isFalse(iterable is Queue, "$name is! Queue");
if (expects.isNotEmpty) {
Expect.equals(expects.first, iterable.first, "$name: first");
Expect.equals(expects.last, iterable.last, "$name: last");
} else {
Expect.throwsStateError(() => iterable.first, "$name: first");
Expect.throwsStateError(() => iterable.last, "$name: last");
}
var it = iterable.iterator;
for (int index = 0; index < expects.length; index++) {
Expect.isTrue(it.moveNext(), "$name: has element $index");
var expect = expects[index];
Expect.equals(expect, it.current, "$name at $index");
Expect.equals(
expect, iterable.elementAt(index), "$name: elementAt($index)");
Expect.isTrue(iterable.contains(expect), "$name:contains $index");
}
Expect.isFalse(it.moveNext(),
"$name: extra element at ${expects.length}: ${it.current}");
} on Error {
print("Failed during: $name");
rethrow;
}
}
main() {
var conversions = <String, Iterable<int> Function(List<int>)>{
"const": toConst,
"list": toList,
"unmod": toUnmodifiable,
"set": toSet,
"queue": toQueue,
"eff-len-iter": toELIter,
"non-eff-iter": toNEIter,
"typed": toTyped,
"keys": toKeys,
"values": toValues,
};
for (var data in [
const <int>[],
const <int>[1],
const <int>[1, 2, 3]
]) {
conversions.forEach((name, c) {
test(data, c(data).whereType<int>(), "$name#${data.length}.wt<int>");
test(data, c(data).whereType<num>(), "$name#${data.length}.wt<num>");
test([], c(data).whereType<Null>(), "$name#${data.length}.wt<Null>");
});
}
test([1, 0.1], ["a", 1, new Object(), 0.1, null].whereType<num>(), "mixed");
var o = new Object();
var a = new A();
var b = new B();
var c = new C();
var d = new D();
var n = null;
test([o, a, b, c, d, n], [o, a, b, c, d, n].whereType<Object>(), "Object");
test([a, b, c, d], [o, a, b, c, d, n].whereType<A>(), "A");
test([b, d], [o, a, b, c, d, n].whereType<B>(), "B");
test([c, d], [o, a, b, c, d, n].whereType<C>(), "C");
test([d], [o, a, b, c, d, n].whereType<D>(), "D");
test([n], [o, a, b, c, d, n].whereType<Null>(), "Null");
test([d], <B>[d].whereType<C>(), "Unrelated");
}
class A {}
class B implements A {}
class C implements A {}
class D implements B, C {}
List<int> toConst(List<int> elements) => elements; // Argument is const.
List<int> toList(List<int> elements) => elements.toList();
List<int> toUnmodifiable(List<int> elements) =>
new List<int>.unmodifiable(elements);
Set<int> toSet(List<int> elements) => elements.toSet();
Queue<int> toQueue(List<int> elements) => new Queue<int>.from(elements);
// Creates an efficient-length iterable.
Iterable<int> toELIter(List<int> elements) => elements.map<int>((x) => x);
// Creates a non-efficient-length iterable.
Iterable<int> toNEIter(List<int> elements) => elements.where((x) => true);
List<int> toTyped(List<int> elements) => new Int32List.fromList(elements);
Iterable<int> toKeys(List<int> elements) =>
new Map<int, int>.fromIterables(elements, elements).keys;
Iterable<int> toValues(List<int> elements) =>
new Map<int, int>.fromIterables(elements, elements).values;