Format packages to new style (#883)
diff --git a/pkgs/async/CHANGELOG.md b/pkgs/async/CHANGELOG.md
index 1f6d74d..5e5d952 100644
--- a/pkgs/async/CHANGELOG.md
+++ b/pkgs/async/CHANGELOG.md
@@ -1,6 +1,7 @@
## 2.13.1-wip
- Fix `StreamGroup.broadcast().close()` to properly complete when all streams in the group close without being explicitly removed.
+- Run `dart format` with the new style.
## 2.13.0
diff --git a/pkgs/async/lib/src/async_cache.dart b/pkgs/async/lib/src/async_cache.dart
index 6fc7cb0..f86b060 100644
--- a/pkgs/async/lib/src/async_cache.dart
+++ b/pkgs/async/lib/src/async_cache.dart
@@ -85,10 +85,15 @@
throw StateError('Previously used to cache via `fetch`');
}
var splitter = _cachedStreamSplitter ??= StreamSplitter(
- callback().transform(StreamTransformer.fromHandlers(handleDone: (sink) {
- _startStaleTimer();
- sink.close();
- })));
+ callback().transform(
+ StreamTransformer.fromHandlers(
+ handleDone: (sink) {
+ _startStaleTimer();
+ sink.close();
+ },
+ ),
+ ),
+ );
return splitter.split();
}
diff --git a/pkgs/async/lib/src/byte_collector.dart b/pkgs/async/lib/src/byte_collector.dart
index 0c93761..a91a732 100644
--- a/pkgs/async/lib/src/byte_collector.dart
+++ b/pkgs/async/lib/src/byte_collector.dart
@@ -28,11 +28,13 @@
/// If any of the input data are not valid bytes, they will be truncated to
/// an eight-bit unsigned value in the resulting list.
CancelableOperation<Uint8List> collectBytesCancelable(
- Stream<List<int>> source) {
+ Stream<List<int>> source,
+) {
return _collectBytes(
- source,
- (subscription, result) => CancelableOperation.fromFuture(result,
- onCancel: subscription.cancel));
+ source,
+ (subscription, result) =>
+ CancelableOperation.fromFuture(result, onCancel: subscription.cancel),
+ );
}
/// Generalization over [collectBytes] and [collectBytesCancelable].
@@ -40,13 +42,19 @@
/// Performs all the same operations, but the final result is created
/// by the [result] function, which has access to the stream subscription
/// so it can cancel the operation.
-T _collectBytes<T>(Stream<List<int>> source,
- T Function(StreamSubscription<List<int>>, Future<Uint8List>) result) {
+T _collectBytes<T>(
+ Stream<List<int>> source,
+ T Function(StreamSubscription<List<int>>, Future<Uint8List>) result,
+) {
var bytes = BytesBuilder(copy: false);
var completer = Completer<Uint8List>.sync();
- var subscription =
- source.listen(bytes.add, onError: completer.completeError, onDone: () {
- completer.complete(bytes.takeBytes());
- }, cancelOnError: true);
+ var subscription = source.listen(
+ bytes.add,
+ onError: completer.completeError,
+ onDone: () {
+ completer.complete(bytes.takeBytes());
+ },
+ cancelOnError: true,
+ );
return result(subscription, completer.future);
}
diff --git a/pkgs/async/lib/src/cancelable_operation.dart b/pkgs/async/lib/src/cancelable_operation.dart
index 2610613..112acbe 100644
--- a/pkgs/async/lib/src/cancelable_operation.dart
+++ b/pkgs/async/lib/src/cancelable_operation.dart
@@ -29,8 +29,10 @@
///
/// Calling this constructor is equivalent to creating a
/// [CancelableCompleter] and completing it with [result].
- factory CancelableOperation.fromFuture(Future<T> result,
- {FutureOr Function()? onCancel}) =>
+ factory CancelableOperation.fromFuture(
+ Future<T> result, {
+ FutureOr Function()? onCancel,
+ }) =>
(CancelableCompleter<T>(onCancel: onCancel)..complete(result)).operation;
/// Creates a [CancelableOperation] which completes to [value].
@@ -51,7 +53,8 @@
/// subscription will be canceled (unlike
/// `CancelableOperation.fromFuture(subscription.asFuture())`).
static CancelableOperation<void> fromSubscription(
- StreamSubscription<void> subscription) {
+ StreamSubscription<void> subscription,
+ ) {
var completer = CancelableCompleter<void>(onCancel: subscription.cancel);
subscription.onDone(completer.complete);
subscription.onError((Object error, StackTrace stackTrace) {
@@ -70,7 +73,8 @@
/// new operation is cancelled, all the [operations] are cancelled as
/// well.
static CancelableOperation<T> race<T>(
- Iterable<CancelableOperation<T>> operations) {
+ Iterable<CancelableOperation<T>> operations,
+ ) {
operations = operations.toList();
if (operations.isEmpty) {
throw ArgumentError('May not be empty', 'operations');
@@ -83,20 +87,25 @@
done = true;
return Future.wait([
for (var operation in operations)
- if (!operation.isCanceled) operation.cancel()
+ if (!operation.isCanceled) operation.cancel(),
]);
}
var completer = CancelableCompleter<T>(onCancel: cancelAll);
for (var operation in operations) {
- operation.then((value) {
- if (!done) cancelAll().whenComplete(() => completer.complete(value));
- }, onError: (error, stackTrace) {
- if (!done) {
- cancelAll()
- .whenComplete(() => completer.completeError(error, stackTrace));
- }
- }, propagateCancel: false);
+ operation.then(
+ (value) {
+ if (!done) cancelAll().whenComplete(() => completer.complete(value));
+ },
+ onError: (error, stackTrace) {
+ if (!done) {
+ cancelAll().whenComplete(
+ () => completer.completeError(error, stackTrace),
+ );
+ }
+ },
+ propagateCancel: false,
+ );
}
return completer.operation;
@@ -114,16 +123,21 @@
/// This is like `value.asStream()`, but if a subscription to the stream is
/// canceled, this operation is as well.
Stream<T> asStream() {
- var controller =
- StreamController<T>(sync: true, onCancel: _completer._cancel);
+ var controller = StreamController<T>(
+ sync: true,
+ onCancel: _completer._cancel,
+ );
- _completer._inner?.future.then((value) {
- controller.add(value);
- controller.close();
- }, onError: (Object error, StackTrace stackTrace) {
- controller.addError(error, stackTrace);
- controller.close();
- });
+ _completer._inner?.future.then(
+ (value) {
+ controller.add(value);
+ controller.close();
+ },
+ onError: (Object error, StackTrace stackTrace) {
+ controller.addError(error, stackTrace);
+ controller.close();
+ },
+ );
return controller.stream;
}
@@ -172,24 +186,28 @@
/// operation is canceled as well. Pass `false` if there are multiple
/// listeners on this operation and canceling the [onValue], [onError], and
/// [onCancel] callbacks should not cancel the other listeners.
- CancelableOperation<R> then<R>(FutureOr<R> Function(T) onValue,
- {FutureOr<R> Function(Object, StackTrace)? onError,
- FutureOr<R> Function()? onCancel,
- bool propagateCancel = true}) =>
- thenOperation<R>((value, completer) {
- completer.complete(onValue(value));
- },
- onError: onError == null
- ? null
- : (error, stackTrace, completer) {
- completer.complete(onError(error, stackTrace));
- },
- onCancel: onCancel == null
- ? null
- : (completer) {
- completer.complete(onCancel());
- },
- propagateCancel: propagateCancel);
+ CancelableOperation<R> then<R>(
+ FutureOr<R> Function(T) onValue, {
+ FutureOr<R> Function(Object, StackTrace)? onError,
+ FutureOr<R> Function()? onCancel,
+ bool propagateCancel = true,
+ }) =>
+ thenOperation<R>(
+ (value, completer) {
+ completer.complete(onValue(value));
+ },
+ onError: onError == null
+ ? null
+ : (error, stackTrace, completer) {
+ completer.complete(onError(error, stackTrace));
+ },
+ onCancel: onCancel == null
+ ? null
+ : (completer) {
+ completer.complete(onCancel());
+ },
+ propagateCancel: propagateCancel,
+ );
/// Creates a new cancelable operation to be completed when this operation
/// completes normally or as an error, or is cancelled.
@@ -222,13 +240,15 @@
/// listeners on this operation and canceling the [onValue], [onError], and
/// [onCancel] callbacks should not cancel the other listeners.
CancelableOperation<R> thenOperation<R>(
- FutureOr<void> Function(T, CancelableCompleter<R>) onValue,
- {FutureOr<void> Function(Object, StackTrace, CancelableCompleter<R>)?
- onError,
- FutureOr<void> Function(CancelableCompleter<R>)? onCancel,
- bool propagateCancel = true}) {
+ FutureOr<void> Function(T, CancelableCompleter<R>) onValue, {
+ FutureOr<void> Function(Object, StackTrace, CancelableCompleter<R>)?
+ onError,
+ FutureOr<void> Function(CancelableCompleter<R>)? onCancel,
+ bool propagateCancel = true,
+ }) {
final completer = CancelableCompleter<R>(
- onCancel: propagateCancel ? _cancelIfNotCanceled : null);
+ onCancel: propagateCancel ? _cancelIfNotCanceled : null,
+ );
// if `_completer._inner` completes before `completer` is cancelled
// call `onValue` or `onError` with the result, and complete `completer`
@@ -246,25 +266,29 @@
// completes before `completer` is cancelled,
// then cancel `cancelCompleter`. (Cancelling twice is safe.)
- _completer._inner?.future.then<void>((value) async {
- if (completer.isCanceled) return;
- try {
- await onValue(value, completer);
- } catch (error, stack) {
- completer.completeError(error, stack);
- }
- },
- onError: onError == null
- ? completer.completeError // Is ignored if already cancelled.
- : (Object error, StackTrace stack) async {
- if (completer.isCanceled) return;
- try {
- await onError(error, stack, completer);
- } catch (error2, stack2) {
- completer.completeErrorIfPending(
- error2, identical(error, error2) ? stack : stack2);
- }
- });
+ _completer._inner?.future.then<void>(
+ (value) async {
+ if (completer.isCanceled) return;
+ try {
+ await onValue(value, completer);
+ } catch (error, stack) {
+ completer.completeError(error, stack);
+ }
+ },
+ onError: onError == null
+ ? completer.completeError // Is ignored if already cancelled.
+ : (Object error, StackTrace stack) async {
+ if (completer.isCanceled) return;
+ try {
+ await onError(error, stack, completer);
+ } catch (error2, stack2) {
+ completer.completeErrorIfPending(
+ error2,
+ identical(error, error2) ? stack : stack2,
+ );
+ }
+ },
+ );
final cancelForwarder = _CancelForwarder<R>(completer, onCancel);
if (_completer.isCanceled) {
cancelForwarder._forward();
@@ -430,11 +454,14 @@
return;
}
- value.then((result) {
- _completeNow()?.complete(result);
- }, onError: (Object error, StackTrace stackTrace) {
- _completeNow()?.completeError(error, stackTrace);
- });
+ value.then(
+ (result) {
+ _completeNow()?.complete(result);
+ },
+ onError: (Object error, StackTrace stackTrace) {
+ _completeNow()?.completeError(error, stackTrace);
+ },
+ );
}
/// Makes this [CancelableCompleter.operation] complete with the same result
@@ -443,8 +470,10 @@
/// If [propagateCancel] is `true` (the default), and the [operation] of this
/// completer is canceled before [result] completes, then [result] is also
/// canceled.
- void completeOperation(CancelableOperation<T> result,
- {bool propagateCancel = true}) {
+ void completeOperation(
+ CancelableOperation<T> result, {
+ bool propagateCancel = true,
+ }) {
if (!_mayComplete) throw StateError('Already completed');
_mayComplete = false;
if (isCanceled) {
@@ -452,14 +481,19 @@
result.value.ignore();
return;
}
- result.then<void>((value) {
- _inner?.complete(
- value); // _inner is set to null if this.operation is cancelled.
- }, onError: (error, stack) {
- _inner?.completeError(error, stack);
- }, onCancel: () {
- operation.cancel();
- });
+ result.then<void>(
+ (value) {
+ _inner?.complete(
+ value,
+ ); // _inner is set to null if this.operation is cancelled.
+ },
+ onError: (error, stack) {
+ _inner?.completeError(error, stack);
+ },
+ onCancel: () {
+ operation.cancel();
+ },
+ );
if (propagateCancel) {
_cancelCompleter?.future.whenComplete(result.cancel);
}
@@ -519,7 +553,7 @@
final isFuture = toReturn is Future;
final cancelFutures = <Future<Object?>>[
if (isFuture) toReturn,
- ...?_cancelForwarders?.map(_forward).nonNulls
+ ...?_cancelForwarders?.map(_forward).nonNulls,
];
final results = (isFuture && cancelFutures.length == 1)
? [await toReturn]
diff --git a/pkgs/async/lib/src/chunked_stream_reader.dart b/pkgs/async/lib/src/chunked_stream_reader.dart
index 1d92216..23c8423 100644
--- a/pkgs/async/lib/src/chunked_stream_reader.dart
+++ b/pkgs/async/lib/src/chunked_stream_reader.dart
@@ -140,7 +140,10 @@
List<T> output;
if (_buffer is Uint8List) {
output = Uint8List.sublistView(
- _buffer as Uint8List, _offset, _offset + size) as List<T>;
+ _buffer as Uint8List,
+ _offset,
+ _offset + size,
+ ) as List<T>;
} else {
output = _buffer.sublist(_offset, _offset + size);
}
diff --git a/pkgs/async/lib/src/delegate/event_sink.dart b/pkgs/async/lib/src/delegate/event_sink.dart
index 34c119b..23c4065 100644
--- a/pkgs/async/lib/src/delegate/event_sink.dart
+++ b/pkgs/async/lib/src/delegate/event_sink.dart
@@ -23,7 +23,8 @@
/// [add] may throw a [TypeError] if the argument type doesn't match the
/// reified type of [sink].
@Deprecated(
- 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)')
+ 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)',
+ )
static EventSink<T> typed<T>(EventSink sink) =>
sink is EventSink<T> ? sink : DelegatingEventSink._(sink);
diff --git a/pkgs/async/lib/src/delegate/sink.dart b/pkgs/async/lib/src/delegate/sink.dart
index a1954f0..a84d6f1 100644
--- a/pkgs/async/lib/src/delegate/sink.dart
+++ b/pkgs/async/lib/src/delegate/sink.dart
@@ -21,7 +21,8 @@
/// throw a [TypeError] if the argument type doesn't match the reified type of
/// [sink].
@Deprecated(
- 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)')
+ 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)',
+ )
static Sink<T> typed<T>(Sink sink) =>
sink is Sink<T> ? sink : DelegatingSink._(sink);
diff --git a/pkgs/async/lib/src/delegate/stream_consumer.dart b/pkgs/async/lib/src/delegate/stream_consumer.dart
index c911c41..9e1fd95 100644
--- a/pkgs/async/lib/src/delegate/stream_consumer.dart
+++ b/pkgs/async/lib/src/delegate/stream_consumer.dart
@@ -23,7 +23,8 @@
/// calls to [addStream] may throw a [TypeError] if the argument type doesn't
/// match the reified type of [consumer].
@Deprecated(
- 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)')
+ 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)',
+ )
static StreamConsumer<T> typed<T>(StreamConsumer consumer) =>
consumer is StreamConsumer<T>
? consumer
diff --git a/pkgs/async/lib/src/delegate/stream_sink.dart b/pkgs/async/lib/src/delegate/stream_sink.dart
index e6edd2f..cd1cd0e 100644
--- a/pkgs/async/lib/src/delegate/stream_sink.dart
+++ b/pkgs/async/lib/src/delegate/stream_sink.dart
@@ -26,7 +26,8 @@
/// throw a [TypeError] if the argument type doesn't match the reified type of
/// [sink].
@Deprecated(
- 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)')
+ 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)',
+ )
static StreamSink<T> typed<T>(StreamSink sink) =>
sink is StreamSink<T> ? sink : DelegatingStreamSink._(sink);
diff --git a/pkgs/async/lib/src/lazy_stream.dart b/pkgs/async/lib/src/lazy_stream.dart
index e0facaa..48fe970 100644
--- a/pkgs/async/lib/src/lazy_stream.dart
+++ b/pkgs/async/lib/src/lazy_stream.dart
@@ -24,8 +24,12 @@
}
@override
- StreamSubscription<T> listen(void Function(T)? onData,
- {Function? onError, void Function()? onDone, bool? cancelOnError}) {
+ StreamSubscription<T> listen(
+ void Function(T)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
var callback = _callback;
if (callback == null) {
throw StateError('Stream has already been listened to.');
@@ -43,7 +47,11 @@
stream = result;
}
- return stream.listen(onData,
- onError: onError, onDone: onDone, cancelOnError: cancelOnError);
+ return stream.listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
}
}
diff --git a/pkgs/async/lib/src/result/result.dart b/pkgs/async/lib/src/result/result.dart
index 124ccef..6164673 100644
--- a/pkgs/async/lib/src/result/result.dart
+++ b/pkgs/async/lib/src/result/result.dart
@@ -44,7 +44,8 @@
static const StreamSinkTransformer<Object, Result<Object>>
captureSinkTransformer =
StreamSinkTransformer<Object, Result<Object>>.fromStreamTransformer(
- CaptureStreamTransformer<Object>());
+ CaptureStreamTransformer<Object>(),
+ );
/// A sink transformer that releases result events.
///
@@ -53,7 +54,8 @@
static const StreamSinkTransformer<Result<Object>, Object>
releaseSinkTransformer =
StreamSinkTransformer<Result<Object>, Object>.fromStreamTransformer(
- ReleaseStreamTransformer<Object>());
+ ReleaseStreamTransformer<Object>(),
+ );
/// Creates a `Result` with the result of calling [computation].
///
diff --git a/pkgs/async/lib/src/single_subscription_transformer.dart b/pkgs/async/lib/src/single_subscription_transformer.dart
index ba6f0d2..b41653b 100644
--- a/pkgs/async/lib/src/single_subscription_transformer.dart
+++ b/pkgs/async/lib/src/single_subscription_transformer.dart
@@ -19,18 +19,24 @@
@override
Stream<T> bind(Stream<S> stream) {
late StreamSubscription<S> subscription;
- var controller =
- StreamController<T>(sync: true, onCancel: () => subscription.cancel());
- subscription = stream.listen((value) {
- // TODO(nweiz): When we release a new major version, get rid of the second
- // type parameter and avoid this conversion.
- try {
- controller.add(value as T);
- // ignore: avoid_catching_errors
- } on TypeError catch (error, stackTrace) {
- controller.addError(error, stackTrace);
- }
- }, onError: controller.addError, onDone: controller.close);
+ var controller = StreamController<T>(
+ sync: true,
+ onCancel: () => subscription.cancel(),
+ );
+ subscription = stream.listen(
+ (value) {
+ // TODO(nweiz): When we release a new major version, get rid of the
+ // second type parameter and avoid this conversion.
+ try {
+ controller.add(value as T);
+ // ignore: avoid_catching_errors
+ } on TypeError catch (error, stackTrace) {
+ controller.addError(error, stackTrace);
+ }
+ },
+ onError: controller.addError,
+ onDone: controller.close,
+ );
return controller.stream;
}
}
diff --git a/pkgs/async/lib/src/sink_base.dart b/pkgs/async/lib/src/sink_base.dart
index f1d7d14..f50256b 100644
--- a/pkgs/async/lib/src/sink_base.dart
+++ b/pkgs/async/lib/src/sink_base.dart
@@ -77,10 +77,14 @@
_addingStream = true;
var completer = Completer<void>.sync();
- stream.listen(onAdd, onError: onError, onDone: () {
- _addingStream = false;
- completer.complete();
- });
+ stream.listen(
+ onAdd,
+ onError: onError,
+ onDone: () {
+ _addingStream = false;
+ completer.complete();
+ },
+ );
return completer.future;
}
diff --git a/pkgs/async/lib/src/stream_closer.dart b/pkgs/async/lib/src/stream_closer.dart
index 9154624..552ac16 100644
--- a/pkgs/async/lib/src/stream_closer.dart
+++ b/pkgs/async/lib/src/stream_closer.dart
@@ -38,7 +38,7 @@
/// ignored.
Future<void> close() => _closeFuture ??= () {
var futures = [
- for (var subscription in _subscriptions) subscription.cancel()
+ for (var subscription in _subscriptions) subscription.cancel(),
];
_subscriptions.clear();
@@ -71,8 +71,10 @@
return;
}
- var subscription =
- stream.listen(controller.add, onError: controller.addError);
+ var subscription = stream.listen(
+ controller.add,
+ onError: controller.addError,
+ );
subscription.onDone(() {
_subscriptions.remove(subscription);
_controllers.remove(controller);
diff --git a/pkgs/async/lib/src/stream_completer.dart b/pkgs/async/lib/src/stream_completer.dart
index 27034c2..b916f03 100644
--- a/pkgs/async/lib/src/stream_completer.dart
+++ b/pkgs/async/lib/src/stream_completer.dart
@@ -117,23 +117,35 @@
Stream<T>? _sourceStream;
@override
- StreamSubscription<T> listen(void Function(T)? onData,
- {Function? onError, void Function()? onDone, bool? cancelOnError}) {
+ StreamSubscription<T> listen(
+ void Function(T)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
if (_controller == null) {
var sourceStream = _sourceStream;
if (sourceStream != null && !sourceStream.isBroadcast) {
// If the source stream is itself single subscription,
// just listen to it directly instead of creating a controller.
- return sourceStream.listen(onData,
- onError: onError, onDone: onDone, cancelOnError: cancelOnError);
+ return sourceStream.listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
}
_ensureController();
if (_sourceStream != null) {
_linkStreamToController();
}
}
- return _controller!.stream.listen(onData,
- onError: onError, onDone: onDone, cancelOnError: cancelOnError);
+ return _controller!.stream.listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
}
/// Whether a source stream has been set.
diff --git a/pkgs/async/lib/src/stream_extensions.dart b/pkgs/async/lib/src/stream_extensions.dart
index 4ba9254..750ee27 100644
--- a/pkgs/async/lib/src/stream_extensions.dart
+++ b/pkgs/async/lib/src/stream_extensions.dart
@@ -22,16 +22,21 @@
if (length < 1) throw RangeError.range(length, 1, null, 'length');
var slice = <T>[];
- return transform(StreamTransformer.fromHandlers(handleData: (data, sink) {
- slice.add(data);
- if (slice.length == length) {
- sink.add(slice);
- slice = [];
- }
- }, handleDone: (sink) {
- if (slice.isNotEmpty) sink.add(slice);
- sink.close();
- }));
+ return transform(
+ StreamTransformer.fromHandlers(
+ handleData: (data, sink) {
+ slice.add(data);
+ if (slice.length == length) {
+ sink.add(slice);
+ slice = [];
+ }
+ },
+ handleDone: (sink) {
+ if (slice.isNotEmpty) sink.add(slice);
+ sink.close();
+ },
+ ),
+ );
}
/// A future which completes with the first event of this stream, or with
@@ -43,10 +48,12 @@
/// completed with `null`.
Future<T?> get firstOrNull {
var completer = Completer<T?>.sync();
- final subscription = listen(null,
- onError: completer.completeError,
- onDone: completer.complete,
- cancelOnError: true);
+ final subscription = listen(
+ null,
+ onError: completer.completeError,
+ onDone: completer.complete,
+ cancelOnError: true,
+ );
subscription.onData((event) {
subscription.cancel().whenComplete(() {
completer.complete(event);
@@ -70,8 +77,11 @@
/// clear that the data isn't not needed.
Stream<T> listenAndBuffer() {
var controller = StreamController<T>(sync: true);
- var subscription = listen(controller.add,
- onError: controller.addError, onDone: controller.close);
+ var subscription = listen(
+ controller.add,
+ onError: controller.addError,
+ onDone: controller.close,
+ );
controller
..onPause = subscription.pause
..onResume = subscription.resume
diff --git a/pkgs/async/lib/src/stream_group.dart b/pkgs/async/lib/src/stream_group.dart
index e02afcd..51da7b9 100644
--- a/pkgs/async/lib/src/stream_group.dart
+++ b/pkgs/async/lib/src/stream_group.dart
@@ -109,17 +109,21 @@
/// Creates a new stream group where [stream] is single-subscriber.
StreamGroup() {
_controller = StreamController<T>(
- onListen: _onListen,
- onPause: _onPause,
- onResume: _onResume,
- onCancel: _onCancel,
- sync: true);
+ onListen: _onListen,
+ onPause: _onPause,
+ onResume: _onResume,
+ onCancel: _onCancel,
+ sync: true,
+ );
}
/// Creates a new stream group where [stream] is a broadcast stream.
StreamGroup.broadcast() {
_controller = StreamController<T>.broadcast(
- onListen: _onListen, onCancel: _onCancelBroadcast, sync: true);
+ onListen: _onListen,
+ onCancel: _onCancelBroadcast,
+ sync: true,
+ );
}
/// Adds [stream] as a member of this group.
@@ -272,8 +276,11 @@
///
/// This will pause the resulting subscription if `this` is paused.
StreamSubscription<T> _listenToStream(Stream<T> stream) {
- var subscription = stream.listen(_controller.add,
- onError: _controller.addError, onDone: () => remove(stream));
+ var subscription = stream.listen(
+ _controller.add,
+ onError: _controller.addError,
+ onDone: () => remove(stream),
+ );
if (_state == _StreamGroupState.paused) subscription.pause();
return subscription;
}
diff --git a/pkgs/async/lib/src/stream_queue.dart b/pkgs/async/lib/src/stream_queue.dart
index c5c0c19..7017a06 100644
--- a/pkgs/async/lib/src/stream_queue.dart
+++ b/pkgs/async/lib/src/stream_queue.dart
@@ -317,7 +317,8 @@
/// }
/// ```
Future<bool> withTransaction(
- Future<bool> Function(StreamQueue<T>) callback) async {
+ Future<bool> Function(StreamQueue<T>) callback,
+ ) async {
var transaction = startTransaction();
var queue = transaction.newQueue();
@@ -356,16 +357,21 @@
/// _stdinQueue.cancelable((queue) => queue.next);
/// ```
CancelableOperation<S> cancelable<S>(
- Future<S> Function(StreamQueue<T>) callback) {
+ Future<S> Function(StreamQueue<T>) callback,
+ ) {
var transaction = startTransaction();
- var completer = CancelableCompleter<S>(onCancel: () {
- transaction.reject();
- });
+ var completer = CancelableCompleter<S>(
+ onCancel: () {
+ transaction.reject();
+ },
+ );
var queue = transaction.newQueue();
- completer.complete(callback(queue).whenComplete(() {
- if (!completer.isCanceled) transaction.commit(queue);
- }));
+ completer.complete(
+ callback(queue).whenComplete(() {
+ if (!completer.isCanceled) transaction.commit(queue);
+ }),
+ );
return completer.operation;
}
@@ -472,14 +478,18 @@
void _ensureListening() {
if (_isDone) return;
if (_subscription == null) {
- _subscription = _source.listen((data) {
- _addResult(Result.value(data));
- }, onError: (Object error, StackTrace stackTrace) {
- _addResult(Result.error(error, stackTrace));
- }, onDone: () {
- _subscription = null;
- _close();
- });
+ _subscription = _source.listen(
+ (data) {
+ _addResult(Result.value(data));
+ },
+ onError: (Object error, StackTrace stackTrace) {
+ _addResult(Result.error(error, stackTrace));
+ },
+ onDone: () {
+ _subscription = null;
+ _close();
+ },
+ );
} else {
_subscription!.resume();
}
@@ -755,7 +765,9 @@
var event = events.removeFirst();
if (event.isError) {
_completer.completeError(
- event.asError!.error, event.asError!.stackTrace);
+ event.asError!.error,
+ event.asError!.stackTrace,
+ );
return true;
}
}
diff --git a/pkgs/async/lib/src/stream_sink_transformer.dart b/pkgs/async/lib/src/stream_sink_transformer.dart
index c1ed747..ebfd4cc 100644
--- a/pkgs/async/lib/src/stream_sink_transformer.dart
+++ b/pkgs/async/lib/src/stream_sink_transformer.dart
@@ -24,7 +24,8 @@
/// This is equivalent to piping all events from the outer sink through a
/// stream transformed by [transformer] and from there into the inner sink.
const factory StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer<S, T> transformer) = StreamTransformerWrapper<S, T>;
+ StreamTransformer<S, T> transformer,
+ ) = StreamTransformerWrapper<S, T>;
/// Creates a [StreamSinkTransformer] that delegates events to the given
/// handlers.
@@ -33,10 +34,11 @@
/// They're called for each incoming event, and any actions on the sink
/// they're passed are forwarded to the inner sink. If a handler is omitted,
/// the event is passed through unaltered.
- factory StreamSinkTransformer.fromHandlers(
- {void Function(S, EventSink<T>)? handleData,
- void Function(Object, StackTrace, EventSink<T>)? handleError,
- void Function(EventSink<T>)? handleDone}) {
+ factory StreamSinkTransformer.fromHandlers({
+ void Function(S, EventSink<T>)? handleData,
+ void Function(Object, StackTrace, EventSink<T>)? handleError,
+ void Function(EventSink<T>)? handleDone,
+ }) {
return HandlerTransformer<S, T>(handleData, handleError, handleDone);
}
@@ -56,7 +58,8 @@
@Deprecated('Will be removed in future version')
// TODO remove TypeSafeStreamSinkTransformer
static StreamSinkTransformer<S, T> typed<S, T>(
- StreamSinkTransformer transformer) =>
+ StreamSinkTransformer transformer,
+ ) =>
transformer is StreamSinkTransformer<S, T>
? transformer
: TypeSafeStreamSinkTransformer(transformer);
diff --git a/pkgs/async/lib/src/stream_sink_transformer/handler_transformer.dart b/pkgs/async/lib/src/stream_sink_transformer/handler_transformer.dart
index 496c7ca..2deaea8 100644
--- a/pkgs/async/lib/src/stream_sink_transformer/handler_transformer.dart
+++ b/pkgs/async/lib/src/stream_sink_transformer/handler_transformer.dart
@@ -68,18 +68,25 @@
if (handleError == null) {
_inner.addError(error, stackTrace);
} else {
- handleError(error, stackTrace ?? AsyncError.defaultStackTrace(error),
- _safeCloseInner);
+ handleError(
+ error,
+ stackTrace ?? AsyncError.defaultStackTrace(error),
+ _safeCloseInner,
+ );
}
}
@override
Future addStream(Stream<S> stream) {
- return _inner.addStream(stream.transform(
+ return _inner.addStream(
+ stream.transform(
StreamTransformer<S, T>.fromHandlers(
- handleData: _transformer._handleData,
- handleError: _transformer._handleError,
- handleDone: _closeSink)));
+ handleData: _transformer._handleData,
+ handleError: _transformer._handleError,
+ handleDone: _closeSink,
+ ),
+ ),
+ );
}
@override
diff --git a/pkgs/async/lib/src/stream_sink_transformer/reject_errors.dart b/pkgs/async/lib/src/stream_sink_transformer/reject_errors.dart
index 6d077f4..fbed1a3 100644
--- a/pkgs/async/lib/src/stream_sink_transformer/reject_errors.dart
+++ b/pkgs/async/lib/src/stream_sink_transformer/reject_errors.dart
@@ -95,8 +95,11 @@
if (_canceled) return Future.value();
var addStreamCompleter = _addStreamCompleter = Completer.sync();
- _addStreamSubscription = stream.listen(_inner.add,
- onError: _addError, onDone: addStreamCompleter.complete);
+ _addStreamSubscription = stream.listen(
+ _inner.add,
+ onError: _addError,
+ onDone: addStreamCompleter.complete,
+ );
return addStreamCompleter.future.then((_) {
_addStreamCompleter = null;
_addStreamSubscription = null;
diff --git a/pkgs/async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart b/pkgs/async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart
index b30e8ad..4f9fb52 100644
--- a/pkgs/async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart
+++ b/pkgs/async/lib/src/stream_sink_transformer/stream_transformer_wrapper.dart
@@ -33,15 +33,19 @@
Future get done => _inner.done;
_StreamTransformerWrapperSink(
- StreamTransformer<S, T> transformer, this._inner) {
- _controller.stream
- .transform(transformer)
- .listen(_inner.add, onError: _inner.addError, onDone: () {
- // Ignore any errors that come from this call to [_inner.close]. The
- // user can access them through [done] or the value returned from
- // [this.close], and we don't want them to get top-leveled.
- _inner.close().catchError((_) {});
- });
+ StreamTransformer<S, T> transformer,
+ this._inner,
+ ) {
+ _controller.stream.transform(transformer).listen(
+ _inner.add,
+ onError: _inner.addError,
+ onDone: () {
+ // Ignore any errors that come from this call to [_inner.close]. The
+ // user can access them through [done] or the value returned from
+ // [this.close], and we don't want them to get top-leveled.
+ _inner.close().catchError((_) {});
+ },
+ );
}
@override
diff --git a/pkgs/async/lib/src/stream_splitter.dart b/pkgs/async/lib/src/stream_splitter.dart
index f7377d6..a02f9d7 100644
--- a/pkgs/async/lib/src/stream_splitter.dart
+++ b/pkgs/async/lib/src/stream_splitter.dart
@@ -76,7 +76,10 @@
}
var controller = StreamController<T>(
- onListen: _onListen, onPause: _onPause, onResume: _onResume);
+ onListen: _onListen,
+ onPause: _onPause,
+ onResume: _onResume,
+ );
controller.onCancel = () => _onCancel(controller);
for (var result in _buffer) {
@@ -144,8 +147,11 @@
// wasn't paused, this will be a no-op.
_subscription!.resume();
} else {
- _subscription =
- _stream.listen(_onData, onError: _onError, onDone: _onDone);
+ _subscription = _stream.listen(
+ _onData,
+ onError: _onError,
+ onDone: _onDone,
+ );
}
}
diff --git a/pkgs/async/lib/src/stream_subscription_transformer.dart b/pkgs/async/lib/src/stream_subscription_transformer.dart
index d03ea70..4706d44 100644
--- a/pkgs/async/lib/src/stream_subscription_transformer.dart
+++ b/pkgs/async/lib/src/stream_subscription_transformer.dart
@@ -27,22 +27,24 @@
/// synchronously call the corresponding method** on the inner
/// [StreamSubscription]: [handleCancel] must call `cancel()`, [handlePause]
/// must call `pause()`, and [handleResume] must call `resume()`.
-StreamTransformer<T, T> subscriptionTransformer<T>(
- {Future Function(StreamSubscription<T>)? handleCancel,
- void Function(StreamSubscription<T>)? handlePause,
- void Function(StreamSubscription<T>)? handleResume}) {
+StreamTransformer<T, T> subscriptionTransformer<T>({
+ Future Function(StreamSubscription<T>)? handleCancel,
+ void Function(StreamSubscription<T>)? handlePause,
+ void Function(StreamSubscription<T>)? handleResume,
+}) {
return StreamTransformer((stream, cancelOnError) {
return _TransformedSubscription(
- stream.listen(null, cancelOnError: cancelOnError),
- handleCancel ?? (inner) => inner.cancel(),
- handlePause ??
- (inner) {
- inner.pause();
- },
- handleResume ??
- (inner) {
- inner.resume();
- });
+ stream.listen(null, cancelOnError: cancelOnError),
+ handleCancel ?? (inner) => inner.cancel(),
+ handlePause ??
+ (inner) {
+ inner.pause();
+ },
+ handleResume ??
+ (inner) {
+ inner.resume();
+ },
+ );
});
}
@@ -65,7 +67,11 @@
bool get isPaused => _inner?.isPaused ?? false;
_TransformedSubscription(
- this._inner, this._handleCancel, this._handlePause, this._handleResume);
+ this._inner,
+ this._handleCancel,
+ this._handlePause,
+ this._handleResume,
+ );
@override
void onData(void Function(T)? handleData) {
diff --git a/pkgs/async/lib/src/stream_zip.dart b/pkgs/async/lib/src/stream_zip.dart
index f5b8296..93f281d 100644
--- a/pkgs/async/lib/src/stream_zip.dart
+++ b/pkgs/async/lib/src/stream_zip.dart
@@ -18,8 +18,12 @@
StreamZip(Iterable<Stream<T>> streams) : _streams = streams;
@override
- StreamSubscription<List<T>> listen(void Function(List<T>)? onData,
- {Function? onError, void Function()? onDone, bool? cancelOnError}) {
+ StreamSubscription<List<T>> listen(
+ void Function(List<T>)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
cancelOnError = identical(true, cancelOnError);
var subscriptions = <StreamSubscription<T>>[];
late StreamController<List<T>> controller;
@@ -71,12 +75,16 @@
try {
for (var stream in _streams) {
var index = subscriptions.length;
- subscriptions.add(stream.listen((data) {
- handleData(index, data);
- },
+ subscriptions.add(
+ stream.listen(
+ (data) {
+ handleData(index, data);
+ },
onError: cancelOnError ? handleError : handleErrorCancel,
onDone: handleDone,
- cancelOnError: cancelOnError));
+ cancelOnError: cancelOnError,
+ ),
+ );
}
} catch (e) {
for (var i = subscriptions.length - 1; i >= 0; i--) {
@@ -87,28 +95,36 @@
current = List<T?>.filled(subscriptions.length, null);
- controller = StreamController<List<T>>(onPause: () {
- for (var i = 0; i < subscriptions.length; i++) {
- // This may pause some subscriptions more than once.
- // These will not be resumed by onResume below, but must wait for the
- // next round.
- subscriptions[i].pause();
- }
- }, onResume: () {
- for (var i = 0; i < subscriptions.length; i++) {
- subscriptions[i].resume();
- }
- }, onCancel: () {
- for (var i = 0; i < subscriptions.length; i++) {
- // Canceling more than once is safe.
- subscriptions[i].cancel();
- }
- });
+ controller = StreamController<List<T>>(
+ onPause: () {
+ for (var i = 0; i < subscriptions.length; i++) {
+ // This may pause some subscriptions more than once.
+ // These will not be resumed by onResume below, but must wait for the
+ // next round.
+ subscriptions[i].pause();
+ }
+ },
+ onResume: () {
+ for (var i = 0; i < subscriptions.length; i++) {
+ subscriptions[i].resume();
+ }
+ },
+ onCancel: () {
+ for (var i = 0; i < subscriptions.length; i++) {
+ // Canceling more than once is safe.
+ subscriptions[i].cancel();
+ }
+ },
+ );
if (subscriptions.isEmpty) {
controller.close();
}
- return controller.stream.listen(onData,
- onError: onError, onDone: onDone, cancelOnError: cancelOnError);
+ return controller.stream.listen(
+ onData,
+ onError: onError,
+ onDone: onDone,
+ cancelOnError: cancelOnError,
+ );
}
}
diff --git a/pkgs/async/lib/src/subscription_stream.dart b/pkgs/async/lib/src/subscription_stream.dart
index e663072..6a7aeb8 100644
--- a/pkgs/async/lib/src/subscription_stream.dart
+++ b/pkgs/async/lib/src/subscription_stream.dart
@@ -40,8 +40,12 @@
}
@override
- StreamSubscription<T> listen(void Function(T)? onData,
- {Function? onError, void Function()? onDone, bool? cancelOnError}) {
+ StreamSubscription<T> listen(
+ void Function(T)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
var subscription = _source;
if (subscription == null) {
throw StateError('Stream has already been listened to.');
diff --git a/pkgs/async/lib/src/typed_stream_transformer.dart b/pkgs/async/lib/src/typed_stream_transformer.dart
index 8a39228..90cd7c3 100644
--- a/pkgs/async/lib/src/typed_stream_transformer.dart
+++ b/pkgs/async/lib/src/typed_stream_transformer.dart
@@ -12,7 +12,8 @@
/// provided. If they're not, the stream throws a [TypeError].
@Deprecated('Use Stream.cast after binding a transformer instead')
StreamTransformer<S, T> typedStreamTransformer<S, T>(
- StreamTransformer transformer) =>
+ StreamTransformer transformer,
+) =>
transformer is StreamTransformer<S, T>
? transformer
: _TypeSafeStreamTransformer(transformer);
diff --git a/pkgs/async/test/async_cache_test.dart b/pkgs/async/test/async_cache_test.dart
index f7c8caa..47204e6 100644
--- a/pkgs/async/test/async_cache_test.dart
+++ b/pkgs/async/test/async_cache_test.dart
@@ -24,8 +24,10 @@
test('should not fetch via callback when a cache exists', () async {
await cache.fetch(() async => 'Expensive');
- expect(await cache.fetch(expectAsync0(() async => 'fake', count: 0)),
- 'Expensive');
+ expect(
+ await cache.fetch(expectAsync0(() async => 'fake', count: 0)),
+ 'Expensive',
+ );
});
group('ephemeral cache', () {
@@ -35,24 +37,29 @@
var completer = Completer<String>();
expect(cache.fetch(() => completer.future), completion('Expensive'));
- expect(cache.fetch(expectAsync0(() async => 'fake', count: 0)),
- completion('Expensive'));
+ expect(
+ cache.fetch(expectAsync0(() async => 'fake', count: 0)),
+ completion('Expensive'),
+ );
completer.complete('Expensive');
});
- test('should fetch via callback when the in-flight future completes',
- () async {
- // No actual caching is done, just avoid duplicate requests.
- cache = AsyncCache.ephemeral();
+ test(
+ 'should fetch via callback when the in-flight future completes',
+ () async {
+ // No actual caching is done, just avoid duplicate requests.
+ cache = AsyncCache.ephemeral();
- var fetched = cache.fetch(() async => 'first');
- expect(fetched, completion('first'));
- expect(
+ var fetched = cache.fetch(() async => 'first');
+ expect(fetched, completion('first'));
+ expect(
cache.fetch(expectAsync0(() async => fail('not called'), count: 0)),
- completion('first'));
- await fetched;
- expect(cache.fetch(() async => 'second'), completion('second'));
- });
+ completion('first'),
+ );
+ await fetched;
+ expect(cache.fetch(() async => 'second'), completion('second'));
+ },
+ );
test('should invalidate even if the future throws an exception', () async {
cache = AsyncCache.ephemeral();
@@ -98,10 +105,13 @@
test('should fetch a stream via a callback', () async {
expect(
- await cache.fetchStream(expectAsync0(() {
+ await cache.fetchStream(
+ expectAsync0(() {
return Stream.fromIterable(['1', '2', '3']);
- })).toList(),
- ['1', '2', '3']);
+ }),
+ ).toList(),
+ ['1', '2', '3'],
+ );
});
test('should not fetch stream via callback when a cache exists', () async {
@@ -111,8 +121,9 @@
yield '3';
}).toList();
expect(
- await cache.fetchStream(expectAsync0(Stream.empty, count: 0)).toList(),
- ['1', '2', '3']);
+ await cache.fetchStream(expectAsync0(Stream.empty, count: 0)).toList(),
+ ['1', '2', '3'],
+ );
});
test('should not fetch stream via callback when request in flight', () async {
@@ -138,16 +149,28 @@
}
expect(await cache.fetchStream(call).toList(), ['Called 1']);
- expect(await cache.fetchStream(call).toList(), ['Called 1'],
+ expect(
+ await cache.fetchStream(call).toList(),
+ [
+ 'Called 1',
+ ],
reason: 'Cache still fresh');
fakeAsync.elapse(const Duration(hours: 1) - const Duration(seconds: 1));
- expect(await cache.fetchStream(call).toList(), ['Called 1'],
+ expect(
+ await cache.fetchStream(call).toList(),
+ [
+ 'Called 1',
+ ],
reason: 'Cache still fresh');
fakeAsync.elapse(const Duration(seconds: 1));
expect(await cache.fetchStream(call).toList(), ['Called 2']);
- expect(await cache.fetchStream(call).toList(), ['Called 2'],
+ expect(
+ await cache.fetchStream(call).toList(),
+ [
+ 'Called 2',
+ ],
reason: 'Cache fresh again');
fakeAsync.elapse(const Duration(hours: 1));
@@ -181,9 +204,11 @@
Stream<String> call() => Stream.fromIterable(['1', '2', '3']);
late StreamSubscription sub;
- sub = cache.fetchStream(call).listen(expectAsync1((event) {
- if (event == '1') sub.pause();
- }));
+ sub = cache.fetchStream(call).listen(
+ expectAsync1((event) {
+ if (event == '1') sub.pause();
+ }),
+ );
expect(cache.fetchStream(call).toList(), completion(['1', '2', '3']));
});
}
diff --git a/pkgs/async/test/byte_collection_test.dart b/pkgs/async/test/byte_collection_test.dart
index 67f319b..63c1136 100644
--- a/pkgs/async/test/byte_collection_test.dart
+++ b/pkgs/async/test/byte_collection_test.dart
@@ -10,12 +10,14 @@
void main() {
group('collectBytes', () {
test('simple list and overflow', () {
- var result = collectBytes(Stream.fromIterable([
- [0],
- [1],
- [2],
- [256]
- ]));
+ var result = collectBytes(
+ Stream.fromIterable([
+ [0],
+ [1],
+ [2],
+ [256],
+ ]),
+ );
expect(result, completion([0, 1, 2, 0]));
});
@@ -30,20 +32,25 @@
});
test('error event', () {
- var result = collectBytes(Stream.fromIterable(
- Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n])));
+ var result = collectBytes(
+ Stream.fromIterable(
+ Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n]),
+ ),
+ );
expect(result, throwsA('badness'));
});
});
group('collectBytes', () {
test('simple list and overflow', () {
- var result = collectBytesCancelable(Stream.fromIterable([
- [0],
- [1],
- [2],
- [256]
- ]));
+ var result = collectBytesCancelable(
+ Stream.fromIterable([
+ [0],
+ [1],
+ [2],
+ [256],
+ ]),
+ );
expect(result.value, completion([0, 1, 2, 0]));
});
@@ -58,8 +65,11 @@
});
test('error event', () {
- var result = collectBytesCancelable(Stream.fromIterable(
- Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n])));
+ var result = collectBytesCancelable(
+ Stream.fromIterable(
+ Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n]),
+ ),
+ );
expect(result.value, throwsA('badness'));
});
diff --git a/pkgs/async/test/cancelable_operation_test.dart b/pkgs/async/test/cancelable_operation_test.dart
index 3b096e4..d7cbcd5 100644
--- a/pkgs/async/test/cancelable_operation_test.dart
+++ b/pkgs/async/test/cancelable_operation_test.dart
@@ -58,36 +58,43 @@
test('sends values from a cancelable operation to the future', () {
expect(completer.operation.value, completion(equals(1)));
- completer
- .completeOperation(CancelableOperation.fromFuture(Future.value(1)));
+ completer.completeOperation(
+ CancelableOperation.fromFuture(Future.value(1)),
+ );
});
- test('sends values from a completed cancelable operation to the future',
- () async {
- final operation = CancelableOperation.fromFuture(Future.value(1));
- await operation.value;
- expect(completer.operation.value, completion(equals(1)));
- completer.completeOperation(operation);
- });
+ test(
+ 'sends values from a completed cancelable operation to the future',
+ () async {
+ final operation = CancelableOperation.fromFuture(Future.value(1));
+ await operation.value;
+ expect(completer.operation.value, completion(equals(1)));
+ completer.completeOperation(operation);
+ },
+ );
test('sends errors from a cancelable operation to the future', () {
expect(completer.operation.value, throwsA('error'));
completer.completeOperation(
- CancelableOperation.fromFuture(Future.error('error')..ignore()));
+ CancelableOperation.fromFuture(Future.error('error')..ignore()),
+ );
});
- test('sends errors from a completed cancelable operation to the future',
- () async {
- final operation =
- CancelableOperation.fromFuture(Future.error('error')..ignore());
- try {
- await operation.value;
- } on Object {
- // ignore
- }
- expect(completer.operation.value, throwsA('error'));
- completer.completeOperation(operation);
- });
+ test(
+ 'sends errors from a completed cancelable operation to the future',
+ () async {
+ final operation = CancelableOperation.fromFuture(
+ Future.error('error')..ignore(),
+ );
+ try {
+ await operation.value;
+ } on Object {
+ // ignore
+ }
+ expect(completer.operation.value, throwsA('error'));
+ completer.completeOperation(operation);
+ },
+ );
test('sends values to valueOrCancellation', () {
expect(completer.operation.valueOrCancellation(), completion(equals(1)));
@@ -132,8 +139,10 @@
test('successfully then with a future', () {
completer.complete(1);
- expect(() => completer.complete(Completer<void>().future),
- throwsStateError);
+ expect(
+ () => completer.complete(Completer<void>().future),
+ throwsStateError,
+ );
});
test('with a future then successfully', () {
@@ -143,8 +152,10 @@
test('with a future twice', () {
completer.complete(Completer<void>().future);
- expect(() => completer.complete(Completer<void>().future),
- throwsStateError);
+ expect(
+ () => completer.complete(Completer<void>().future),
+ throwsStateError,
+ );
});
});
@@ -164,8 +175,9 @@
test('forwards a done event once it completes', () async {
var controller = StreamController<void>();
var operationCompleted = false;
- CancelableOperation.fromSubscription(controller.stream.listen(null))
- .then((_) {
+ CancelableOperation.fromSubscription(
+ controller.stream.listen(null),
+ ).then((_) {
operationCompleted = true;
});
@@ -179,7 +191,8 @@
test('forwards errors', () {
var operation = CancelableOperation.fromSubscription(
- Stream.error('error').listen(null));
+ Stream.error('error').listen(null),
+ );
expect(operation.value, throwsA('error'));
});
});
@@ -200,10 +213,12 @@
test('fires onCancel', () {
var canceled = false;
late CancelableCompleter completer;
- completer = CancelableCompleter(onCancel: expectAsync0(() {
- expect(completer.isCanceled, isTrue);
- canceled = true;
- }));
+ completer = CancelableCompleter(
+ onCancel: expectAsync0(() {
+ expect(completer.isCanceled, isTrue);
+ canceled = true;
+ }),
+ );
expect(canceled, isFalse);
expect(completer.isCanceled, isFalse);
@@ -219,9 +234,11 @@
});
test('returns the onCancel future each time cancel is called', () {
- var completer = CancelableCompleter(onCancel: expectAsync0(() {
- return Future.value(1);
- }));
+ var completer = CancelableCompleter(
+ onCancel: expectAsync0(() {
+ return Future.value(1);
+ }),
+ );
expect(completer.operation.cancel(), completion(equals(1)));
expect(completer.operation.cancel(), completion(equals(1)));
expect(completer.operation.cancel(), completion(equals(1)));
@@ -233,8 +250,9 @@
});
test("doesn't call onCancel if the completer has completed", () {
- var completer =
- CancelableCompleter(onCancel: expectAsync0(() {}, count: 0));
+ var completer = CancelableCompleter(
+ onCancel: expectAsync0(() {}, count: 0),
+ );
completer.complete(1);
expect(completer.operation.value, completion(equals(1)));
expect(completer.operation.cancel(), completes);
@@ -251,8 +269,9 @@
test(
"doesn't call onCancel if the completer has completed to a fired "
'Future', () async {
- var completer =
- CancelableCompleter(onCancel: expectAsync0(() {}, count: 0));
+ var completer = CancelableCompleter(
+ onCancel: expectAsync0(() {}, count: 0),
+ );
completer.complete(Future.value(1));
await completer.operation.value;
expect(completer.operation.cancel(), completes);
@@ -273,17 +292,20 @@
});
test('pipes an error through valueOrCancellation', () {
- var completer = CancelableCompleter(onCancel: () {
- throw 'error';
- });
+ var completer = CancelableCompleter(
+ onCancel: () {
+ throw 'error';
+ },
+ );
expect(completer.operation.valueOrCancellation(1), throwsA('error'));
completer.operation.cancel();
});
test('valueOrCancellation waits on the onCancel future', () async {
var innerCompleter = Completer<void>();
- var completer =
- CancelableCompleter(onCancel: () => innerCompleter.future);
+ var completer = CancelableCompleter(
+ onCancel: () => innerCompleter.future,
+ );
var fired = false;
completer.operation.valueOrCancellation().then((_) {
@@ -299,63 +321,72 @@
expect(fired, isTrue);
});
- test('CancelableOperation.fromSubscription() cancels the subscription',
- () async {
- var cancelCompleter = Completer<void>();
- var canceled = false;
- var controller = StreamController<void>(onCancel: () {
- canceled = true;
- return cancelCompleter.future;
- });
- var operation =
- CancelableOperation.fromSubscription(controller.stream.listen(null));
+ test(
+ 'CancelableOperation.fromSubscription() cancels the subscription',
+ () async {
+ var cancelCompleter = Completer<void>();
+ var canceled = false;
+ var controller = StreamController<void>(
+ onCancel: () {
+ canceled = true;
+ return cancelCompleter.future;
+ },
+ );
+ var operation = CancelableOperation.fromSubscription(
+ controller.stream.listen(null),
+ );
- await flushMicrotasks();
- expect(canceled, isFalse);
+ await flushMicrotasks();
+ expect(canceled, isFalse);
- // The `cancel()` call shouldn't complete until
- // `StreamSubscription.cancel` completes.
- var cancelCompleted = false;
- expect(
+ // The `cancel()` call shouldn't complete until
+ // `StreamSubscription.cancel` completes.
+ var cancelCompleted = false;
+ expect(
operation.cancel().then((_) {
cancelCompleted = true;
}),
- completes);
- await flushMicrotasks();
- expect(canceled, isTrue);
- expect(cancelCompleted, isFalse);
+ completes,
+ );
+ await flushMicrotasks();
+ expect(canceled, isTrue);
+ expect(cancelCompleted, isFalse);
- cancelCompleter.complete();
- await flushMicrotasks();
- expect(cancelCompleted, isTrue);
- });
+ cancelCompleter.complete();
+ await flushMicrotasks();
+ expect(cancelCompleted, isTrue);
+ },
+ );
group('completeOperation', () {
test('sends cancellation from a cancelable operation', () async {
final completer = CancelableCompleter<void>();
completer.operation.value.whenComplete(expectAsync0(() {}, count: 0));
- completer
- .completeOperation(CancelableCompleter<void>().operation..cancel());
+ completer.completeOperation(
+ CancelableCompleter<void>().operation..cancel(),
+ );
await completer.operation.valueOrCancellation();
expect(completer.operation.isCanceled, true);
});
- test('sends errors from a completed cancelable operation to the future',
- () async {
- final operation = CancelableCompleter<void>().operation..cancel();
- await operation.valueOrCancellation();
- final completer = CancelableCompleter<void>();
- completer.operation.value.whenComplete(expectAsync0(() {}, count: 0));
- completer.completeOperation(operation);
- await completer.operation.valueOrCancellation();
- expect(completer.operation.isCanceled, true);
- });
+ test(
+ 'sends errors from a completed cancelable operation to the future',
+ () async {
+ final operation = CancelableCompleter<void>().operation..cancel();
+ await operation.valueOrCancellation();
+ final completer = CancelableCompleter<void>();
+ completer.operation.value.whenComplete(expectAsync0(() {}, count: 0));
+ completer.completeOperation(operation);
+ await completer.operation.valueOrCancellation();
+ expect(completer.operation.isCanceled, true);
+ },
+ );
test('propagates cancellation', () {
final completer = CancelableCompleter<void>();
- final operation =
- CancelableCompleter<void>(onCancel: expectAsync0(() {}, count: 1))
- .operation;
+ final operation = CancelableCompleter<void>(
+ onCancel: expectAsync0(() {}, count: 1),
+ ).operation;
completer.completeOperation(operation);
completer.operation.cancel();
});
@@ -363,29 +394,31 @@
test('propagates cancellation from already canceld completer', () async {
final completer = CancelableCompleter<void>()..operation.cancel();
await completer.operation.valueOrCancellation();
- final operation =
- CancelableCompleter<void>(onCancel: expectAsync0(() {}, count: 1))
- .operation;
+ final operation = CancelableCompleter<void>(
+ onCancel: expectAsync0(() {}, count: 1),
+ ).operation;
completer.completeOperation(operation);
});
test('cancel propagation can be disabled', () {
final completer = CancelableCompleter<void>();
- final operation =
- CancelableCompleter<void>(onCancel: expectAsync0(() {}, count: 0))
- .operation;
+ final operation = CancelableCompleter<void>(
+ onCancel: expectAsync0(() {}, count: 0),
+ ).operation;
completer.completeOperation(operation, propagateCancel: false);
completer.operation.cancel();
});
- test('cancel propagation can be disabled from already canceled completed',
- () async {
- final completer = CancelableCompleter<void>()..operation.cancel();
- await completer.operation.valueOrCancellation();
- final operation =
- CancelableCompleter<void>(onCancel: expectAsync0(() {}, count: 0))
- .operation;
- completer.completeOperation(operation, propagateCancel: false);
- });
+ test(
+ 'cancel propagation can be disabled from already canceled completed',
+ () async {
+ final completer = CancelableCompleter<void>()..operation.cancel();
+ await completer.operation.valueOrCancellation();
+ final operation = CancelableCompleter<void>(
+ onCancel: expectAsync0(() {}, count: 0),
+ ).operation;
+ completer.completeOperation(operation, propagateCancel: false);
+ },
+ );
});
});
@@ -406,8 +439,9 @@
test('cancels the completer when the subscription is canceled', () {
var completer = CancelableCompleter(onCancel: expectAsync0(() {}));
- var sub =
- completer.operation.asStream().listen(expectAsync1((_) {}, count: 0));
+ var sub = completer.operation.asStream().listen(
+ expectAsync1((_) {}, count: 0),
+ );
completer.operation.value.whenComplete(expectAsync0(() {}, count: 0));
sub.cancel();
expect(completer.isCanceled, isTrue);
@@ -431,10 +465,12 @@
});
CancelableOperation<String> runThen() {
- return originalCompleter.operation.then(onValue!,
- onError: onError,
- onCancel: onCancel,
- propagateCancel: propagateCancel);
+ return originalCompleter.operation.then(
+ onValue!,
+ onError: onError,
+ onCancel: onCancel,
+ propagateCancel: propagateCancel,
+ );
}
group('original operation completes successfully', () {
@@ -454,22 +490,27 @@
});
test('onValue returns Future that throws error', () {
- onValue =
- expectAsync1((v) => Future.error('error'), count: 1, id: 'onValue');
+ onValue = expectAsync1(
+ (v) => Future.error('error'),
+ count: 1,
+ id: 'onValue',
+ );
expect(runThen().value, throwsA('error'));
originalCompleter.complete(1);
});
- test('and returned operation is canceled with propagateCancel = false',
- () async {
- propagateCancel = false;
+ test(
+ 'and returned operation is canceled with propagateCancel = false',
+ () async {
+ propagateCancel = false;
- runThen().cancel();
+ runThen().cancel();
- // onValue should not be called.
- originalCompleter.complete(1);
- });
+ // onValue should not be called.
+ originalCompleter.complete(1);
+ },
+ );
});
group('original operation completes with error', () {
@@ -481,8 +522,11 @@
});
test('onError completes successfully', () {
- onError = expectAsync2((e, s) => 'onError caught $e',
- count: 1, id: 'onError');
+ onError = expectAsync2(
+ (e, s) => 'onError caught $e',
+ count: 1,
+ id: 'onError',
+ );
expect(runThen().value, completion('onError caught error'));
originalCompleter.completeError('error');
@@ -497,22 +541,27 @@
});
test('onError returns Future that throws', () {
- onError = expectAsync2((e, s) => Future.error('onError caught $e'),
- count: 1, id: 'onError');
+ onError = expectAsync2(
+ (e, s) => Future.error('onError caught $e'),
+ count: 1,
+ id: 'onError',
+ );
expect(runThen().value, throwsA('onError caught error'));
originalCompleter.completeError('error');
});
- test('and returned operation is canceled with propagateCancel = false',
- () async {
- propagateCancel = false;
+ test(
+ 'and returned operation is canceled with propagateCancel = false',
+ () async {
+ propagateCancel = false;
- runThen().cancel();
+ runThen().cancel();
- // onError should not be called.
- originalCompleter.completeError('error');
- });
+ // onError should not be called.
+ originalCompleter.completeError('error');
+ },
+ );
});
group('original operation canceled', () {
@@ -541,27 +590,32 @@
});
test('onCancel returns Future that throws error', () {
- onCancel =
- expectAsync0(() => Future.error('error'), count: 1, id: 'onCancel');
+ onCancel = expectAsync0(
+ () => Future.error('error'),
+ count: 1,
+ id: 'onCancel',
+ );
expect(runThen().value, throwsA('error'));
originalCompleter.operation.cancel();
});
- test('after completing with a future does not invoke `onValue`',
- () async {
- onValue = expectAsync1((_) => '', count: 0);
- onCancel = null;
- var operation = runThen();
- var workCompleter = Completer<int>();
- originalCompleter.complete(workCompleter.future);
- var cancelation = originalCompleter.operation.cancel();
- expect(originalCompleter.isCanceled, true);
- workCompleter.complete(0);
- await cancelation;
- expect(operation.isCanceled, true);
- await workCompleter.future;
- });
+ test(
+ 'after completing with a future does not invoke `onValue`',
+ () async {
+ onValue = expectAsync1((_) => '', count: 0);
+ onCancel = null;
+ var operation = runThen();
+ var workCompleter = Completer<int>();
+ originalCompleter.complete(workCompleter.future);
+ var cancelation = originalCompleter.operation.cancel();
+ expect(originalCompleter.isCanceled, true);
+ workCompleter.complete(0);
+ await cancelation;
+ expect(operation.isCanceled, true);
+ await workCompleter.future;
+ },
+ );
test('after the value is completed invokes `onValue`', () {
onValue = expectAsync1((_) => 'foo', count: 1);
@@ -652,8 +706,11 @@
setUp(() {
// Initialize all functions to ones that expect to not be called.
- onValue = expectAsync2((value, completer) => completer.complete('$value'),
- count: 0, id: 'onValue');
+ onValue = expectAsync2(
+ (value, completer) => completer.complete('$value'),
+ count: 0,
+ id: 'onValue',
+ );
onError = null;
onCancel = null;
propagateCancel = false;
@@ -661,16 +718,21 @@
});
CancelableOperation<String> runThenOperation() {
- return originalCompleter.operation.thenOperation(onValue,
- onError: onError,
- onCancel: onCancel,
- propagateCancel: propagateCancel);
+ return originalCompleter.operation.thenOperation(
+ onValue,
+ onError: onError,
+ onCancel: onCancel,
+ propagateCancel: propagateCancel,
+ );
}
group('original operation completes successfully', () {
test('onValue completes successfully', () {
- onValue =
- expectAsync2((v, c) => c.complete('$v'), count: 1, id: 'onValue');
+ onValue = expectAsync2(
+ (v, c) => c.complete('$v'),
+ count: 1,
+ id: 'onValue',
+ );
expect(runThenOperation().value, completion('1'));
originalCompleter.complete(1);
@@ -686,17 +748,21 @@
test('onValue completes operation as error', () {
onValue = expectAsync2(
- (_, completer) => completer.completeError('error'),
- count: 1,
- id: 'onValue');
+ (_, completer) => completer.completeError('error'),
+ count: 1,
+ id: 'onValue',
+ );
expect(runThenOperation().value, throwsA('error'));
originalCompleter.complete(1);
});
test('onValue returns a Future that throws error', () {
- onValue = expectAsync2((_, completer) => Future.error('error'),
- count: 1, id: 'onValue');
+ onValue = expectAsync2(
+ (_, completer) => Future.error('error'),
+ count: 1,
+ id: 'onValue',
+ );
expect(runThenOperation().value, throwsA('error'));
originalCompleter.complete(1);
@@ -719,8 +785,11 @@
});
test('onError completes operation', () {
- onError = expectAsync3((e, s, c) => c.complete('onError caught $e'),
- count: 1, id: 'onError');
+ onError = expectAsync3(
+ (e, s, c) => c.complete('onError caught $e'),
+ count: 1,
+ id: 'onError',
+ );
expect(runThenOperation().value, completion('onError caught error'));
originalCompleter.completeError('error');
@@ -735,8 +804,11 @@
});
test('onError returns Future that throws error', () {
- onError = expectAsync3((e, s, c) => Future.error('onError caught $e'),
- count: 1, id: 'onError');
+ onError = expectAsync3(
+ (e, s, c) => Future.error('onError caught $e'),
+ count: 1,
+ id: 'onError',
+ );
expect(runThenOperation().value, throwsA('onError caught error'));
originalCompleter.completeError('error');
@@ -744,23 +816,26 @@
test('onError completes operation as an error', () {
onError = expectAsync3(
- (e, s, c) => c.completeError('onError caught $e'),
- count: 1,
- id: 'onError');
+ (e, s, c) => c.completeError('onError caught $e'),
+ count: 1,
+ id: 'onError',
+ );
expect(runThenOperation().value, throwsA('onError caught error'));
originalCompleter.completeError('error');
});
- test('and returned operation is canceled with propagateCancel = false',
- () async {
- onError = expectAsync3((e, s, c) {}, count: 0);
+ test(
+ 'and returned operation is canceled with propagateCancel = false',
+ () async {
+ onError = expectAsync3((e, s, c) {}, count: 0);
- runThenOperation().cancel();
+ runThenOperation().cancel();
- // onError should not be called.
- originalCompleter.completeError('error');
- });
+ // onError should not be called.
+ originalCompleter.completeError('error');
+ },
+ );
});
group('original operation canceled', () {
@@ -774,8 +849,11 @@
});
test('onCancel completes successfully', () {
- onCancel = expectAsync1((c) => c.complete('canceled'),
- count: 1, id: 'onCancel');
+ onCancel = expectAsync1(
+ (c) => c.complete('canceled'),
+ count: 1,
+ id: 'onCancel',
+ );
expect(runThenOperation().value, completion('canceled'));
originalCompleter.operation.cancel();
@@ -790,35 +868,43 @@
});
test('onCancel completes operation as error', () {
- onCancel = expectAsync1((c) => c.completeError('error'),
- count: 1, id: 'onCancel');
+ onCancel = expectAsync1(
+ (c) => c.completeError('error'),
+ count: 1,
+ id: 'onCancel',
+ );
expect(runThenOperation().value, throwsA('error'));
originalCompleter.operation.cancel();
});
test('onCancel returns Future that throws error', () {
- onCancel = expectAsync1((c) => Future.error('error'),
- count: 1, id: 'onCancel');
+ onCancel = expectAsync1(
+ (c) => Future.error('error'),
+ count: 1,
+ id: 'onCancel',
+ );
expect(runThenOperation().value, throwsA('error'));
originalCompleter.operation.cancel();
});
- test('after completing with a future does not invoke `onValue`',
- () async {
- onValue = expectAsync2((_, __) {}, count: 0);
- onCancel = null;
- var operation = runThenOperation();
- var workCompleter = Completer<int>();
- originalCompleter.complete(workCompleter.future);
- var cancelation = originalCompleter.operation.cancel();
- expect(originalCompleter.isCanceled, true);
- workCompleter.complete(0);
- await cancelation;
- expect(operation.isCanceled, true);
- await workCompleter.future;
- });
+ test(
+ 'after completing with a future does not invoke `onValue`',
+ () async {
+ onValue = expectAsync2((_, __) {}, count: 0);
+ onCancel = null;
+ var operation = runThenOperation();
+ var workCompleter = Completer<int>();
+ originalCompleter.complete(workCompleter.future);
+ var cancelation = originalCompleter.operation.cancel();
+ expect(originalCompleter.isCanceled, true);
+ workCompleter.complete(0);
+ await cancelation;
+ expect(operation.isCanceled, true);
+ await workCompleter.future;
+ },
+ );
test('after the value is completed invokes `onValue`', () {
onValue = expectAsync2((v, c) => c.complete('foo'), count: 1);
@@ -881,22 +967,31 @@
late CancelableOperation<int> operation;
setUp(() {
canceled1 = false;
- completer1 = CancelableCompleter<int>(onCancel: () {
- canceled1 = true;
- });
+ completer1 = CancelableCompleter<int>(
+ onCancel: () {
+ canceled1 = true;
+ },
+ );
canceled2 = false;
- completer2 = CancelableCompleter<int>(onCancel: () {
- canceled2 = true;
- });
+ completer2 = CancelableCompleter<int>(
+ onCancel: () {
+ canceled2 = true;
+ },
+ );
canceled3 = false;
- completer3 = CancelableCompleter<int>(onCancel: () {
- canceled3 = true;
- });
+ completer3 = CancelableCompleter<int>(
+ onCancel: () {
+ canceled3 = true;
+ },
+ );
- operation = CancelableOperation.race(
- [completer1.operation, completer2.operation, completer3.operation]);
+ operation = CancelableOperation.race([
+ completer1.operation,
+ completer2.operation,
+ completer3.operation,
+ ]);
});
test('returns the first value to complete', () {
diff --git a/pkgs/async/test/chunked_stream_reader.dart b/pkgs/async/test/chunked_stream_reader.dart
index 2fc1e8b..cf47982 100644
--- a/pkgs/async/test/chunked_stream_reader.dart
+++ b/pkgs/async/test/chunked_stream_reader.dart
@@ -324,10 +324,9 @@
});
test('readChunk() until exact end of stream', () async {
- final stream = Stream.fromIterable(Iterable.generate(
- 10,
- (_) => Uint8List(512),
- ));
+ final stream = Stream.fromIterable(
+ Iterable.generate(10, (_) => Uint8List(512)),
+ );
final r = ChunkedStreamReader(stream);
while (true) {
diff --git a/pkgs/async/test/future_group_test.dart b/pkgs/async/test/future_group_test.dart
index 9729c06..effca5b 100644
--- a/pkgs/async/test/future_group_test.dart
+++ b/pkgs/async/test/future_group_test.dart
@@ -110,20 +110,22 @@
expect(futureGroup.future, completion(equals([1, 2, 3])));
});
- test("completes to the first error to be emitted, even if it's not closed",
- () {
- var completer1 = Completer<void>();
- var completer2 = Completer<void>();
- var completer3 = Completer<void>();
+ test(
+ "completes to the first error to be emitted, even if it's not closed",
+ () {
+ var completer1 = Completer<void>();
+ var completer2 = Completer<void>();
+ var completer3 = Completer<void>();
- futureGroup.add(completer1.future);
- futureGroup.add(completer2.future);
- futureGroup.add(completer3.future);
+ futureGroup.add(completer1.future);
+ futureGroup.add(completer2.future);
+ futureGroup.add(completer3.future);
- completer2.completeError('error 2');
- completer1.completeError('error 1');
- expect(futureGroup.future, throwsA('error 2'));
- });
+ completer2.completeError('error 2');
+ completer1.completeError('error 1');
+ expect(futureGroup.future, throwsA('error 2'));
+ },
+ );
group('onIdle:', () {
test('emits an event when the last pending future completes', () async {
@@ -191,20 +193,25 @@
var onIdleDone = false;
var futureFired = false;
- futureGroup.onIdle.listen(expectAsync1((_) {
- expect(futureFired, isFalse);
- idle = true;
- }), onDone: expectAsync0(() {
- expect(idle, isTrue);
- expect(futureFired, isFalse);
- onIdleDone = true;
- }));
+ futureGroup.onIdle.listen(
+ expectAsync1((_) {
+ expect(futureFired, isFalse);
+ idle = true;
+ }),
+ onDone: expectAsync0(() {
+ expect(idle, isTrue);
+ expect(futureFired, isFalse);
+ onIdleDone = true;
+ }),
+ );
- futureGroup.future.then(expectAsync1((_) {
- expect(idle, isTrue);
- expect(onIdleDone, isTrue);
- futureFired = true;
- }));
+ futureGroup.future.then(
+ expectAsync1((_) {
+ expect(idle, isTrue);
+ expect(onIdleDone, isTrue);
+ futureFired = true;
+ }),
+ );
var completer = Completer<void>();
futureGroup.add(completer.future);
diff --git a/pkgs/async/test/lazy_stream_test.dart b/pkgs/async/test/lazy_stream_test.dart
index 9785b2e..064a032 100644
--- a/pkgs/async/test/lazy_stream_test.dart
+++ b/pkgs/async/test/lazy_stream_test.dart
@@ -12,10 +12,12 @@
void main() {
test('calls the callback when the stream is listened', () async {
var callbackCalled = false;
- var stream = LazyStream(expectAsync0(() {
- callbackCalled = true;
- return const Stream.empty();
- }));
+ var stream = LazyStream(
+ expectAsync0(() {
+ callbackCalled = true;
+ return const Stream.empty();
+ }),
+ );
await flushMicrotasks();
expect(callbackCalled, isFalse);
@@ -26,10 +28,12 @@
test('calls the callback when the stream is listened', () async {
var callbackCalled = false;
- var stream = LazyStream(expectAsync0(() {
- callbackCalled = true;
- return const Stream.empty();
- }));
+ var stream = LazyStream(
+ expectAsync0(() {
+ callbackCalled = true;
+ return const Stream.empty();
+ }),
+ );
await flushMicrotasks();
expect(callbackCalled, isFalse);
@@ -93,10 +97,12 @@
test("a lazy stream can't be listened to from within its callback", () {
late LazyStream stream;
- stream = LazyStream(expectAsync0(() {
- expect(() => stream.listen(null), throwsStateError);
- return const Stream.empty();
- }));
+ stream = LazyStream(
+ expectAsync0(() {
+ expect(() => stream.listen(null), throwsStateError);
+ return const Stream.empty();
+ }),
+ );
stream.listen(null);
});
}
diff --git a/pkgs/async/test/null_stream_sink_test.dart b/pkgs/async/test/null_stream_sink_test.dart
index 16d6986..79527da 100644
--- a/pkgs/async/test/null_stream_sink_test.dart
+++ b/pkgs/async/test/null_stream_sink_test.dart
@@ -58,9 +58,11 @@
test('listens to the stream then cancels immediately', () async {
var sink = NullStreamSink();
var canceled = false;
- var controller = StreamController(onCancel: () {
- canceled = true;
- });
+ var controller = StreamController(
+ onCancel: () {
+ canceled = true;
+ },
+ );
expect(sink.addStream(controller.stream), completes);
await flushMicrotasks();
@@ -90,19 +92,21 @@
expect(sink.addStream(controller.stream), throwsA('oh no'));
});
- test('causes events to throw StateErrors until the future completes',
- () async {
- var sink = NullStreamSink();
- var future = sink.addStream(const Stream.empty());
- expect(() => sink.add(1), throwsStateError);
- expect(() => sink.addError('oh no'), throwsStateError);
- expect(() => sink.addStream(const Stream.empty()), throwsStateError);
+ test(
+ 'causes events to throw StateErrors until the future completes',
+ () async {
+ var sink = NullStreamSink();
+ var future = sink.addStream(const Stream.empty());
+ expect(() => sink.add(1), throwsStateError);
+ expect(() => sink.addError('oh no'), throwsStateError);
+ expect(() => sink.addStream(const Stream.empty()), throwsStateError);
- await future;
- sink.add(1);
- sink.addError('oh no');
- expect(sink.addStream(const Stream.empty()), completes);
- });
+ await future;
+ sink.add(1);
+ sink.addError('oh no');
+ expect(sink.addStream(const Stream.empty()), completes);
+ },
+ );
});
});
diff --git a/pkgs/async/test/reject_errors_test.dart b/pkgs/async/test/reject_errors_test.dart
index 27e3c25..c432f23 100644
--- a/pkgs/async/test/reject_errors_test.dart
+++ b/pkgs/async/test/reject_errors_test.dart
@@ -74,8 +74,9 @@
test('cancels the current subscription', () async {
var inputCanceled = false;
- var inputController =
- StreamController(onCancel: () => inputCanceled = true);
+ var inputController = StreamController(
+ onCancel: () => inputCanceled = true,
+ );
var transformed = controller.sink.rejectErrors()
..addStream(inputController.stream);
@@ -124,7 +125,8 @@
var addStreamCancelled = false;
transformed.addStream(
- StreamController(onCancel: () => addStreamCancelled = true).stream);
+ StreamController(onCancel: () => addStreamCancelled = true).stream,
+ );
await pumpEventQueue();
expect(addStreamCancelled, isFalse);
@@ -138,22 +140,27 @@
var transformed = NullStreamSink(done: completer.future).rejectErrors();
expect(
- transformed.addStream(
- StreamController(onCancel: () => throw 'oh no').stream),
- throwsA('oh no'));
+ transformed.addStream(
+ StreamController(onCancel: () => throw 'oh no').stream,
+ ),
+ throwsA('oh no'),
+ );
completer.complete();
});
group('forwards its error', () {
test('through done', () async {
- expect(NullStreamSink(done: Future.error('oh no')).rejectErrors().done,
- throwsA('oh no'));
+ expect(
+ NullStreamSink(done: Future.error('oh no')).rejectErrors().done,
+ throwsA('oh no'),
+ );
});
test('through close', () async {
expect(
- NullStreamSink(done: Future.error('oh no')).rejectErrors().close(),
- throwsA('oh no'));
+ NullStreamSink(done: Future.error('oh no')).rejectErrors().close(),
+ throwsA('oh no'),
+ );
});
});
});
diff --git a/pkgs/async/test/restartable_timer_test.dart b/pkgs/async/test/restartable_timer_test.dart
index 4aab287..a0c117e 100644
--- a/pkgs/async/test/restartable_timer_test.dart
+++ b/pkgs/async/test/restartable_timer_test.dart
@@ -100,7 +100,9 @@
test("only runs the callback once if the timer isn't reset", () {
FakeAsync().run((async) {
RestartableTimer(
- const Duration(seconds: 5), expectAsync0(() {}, count: 1));
+ const Duration(seconds: 5),
+ expectAsync0(() {}, count: 1),
+ );
async.elapse(const Duration(seconds: 10));
});
});
diff --git a/pkgs/async/test/result/result_captureAll_test.dart b/pkgs/async/test/result/result_captureAll_test.dart
index e85999e..4c31666 100644
--- a/pkgs/async/test/result/result_captureAll_test.dart
+++ b/pkgs/async/test/result/result_captureAll_test.dart
@@ -17,8 +17,10 @@
Result err(int n) => ErrorResult('$n', someStack);
/// Helper function creating an iterable of futures.
-Iterable<Future<int>> futures(int count,
- {bool Function(int index)? throwWhen}) sync* {
+Iterable<Future<int>> futures(
+ int count, {
+ bool Function(int index)? throwWhen,
+}) sync* {
for (var i = 0; i < count; i++) {
if (throwWhen != null && throwWhen(i)) {
yield Future<int>.error('$i', someStack);
@@ -46,20 +48,23 @@
});
test('error only', () async {
- var all =
- await Result.captureAll<int>(futures(1, throwWhen: (_) => true));
+ var all = await Result.captureAll<int>(
+ futures(1, throwWhen: (_) => true),
+ );
expect(all, [err(0)]);
});
test('multiple error only', () async {
- var all =
- await Result.captureAll<int>(futures(3, throwWhen: (_) => true));
+ var all = await Result.captureAll<int>(
+ futures(3, throwWhen: (_) => true),
+ );
expect(all, [err(0), err(1), err(2)]);
});
test('mixed error and value', () async {
- var all =
- await Result.captureAll<int>(futures(4, throwWhen: (x) => x.isOdd));
+ var all = await Result.captureAll<int>(
+ futures(4, throwWhen: (x) => x.isOdd),
+ );
expect(all, [res(0), err(1), res(2), err(3)]);
});
@@ -185,7 +190,7 @@
Future<int>(() => 2),
3,
Future<int>(() async => await Future.error('4', someStack)),
- Future<int>.value(5)
+ Future<int>.value(5),
]);
expect(all, [res(1), res(2), res(3), err(4), res(5)]);
});
diff --git a/pkgs/async/test/result/result_flattenAll_test.dart b/pkgs/async/test/result/result_flattenAll_test.dart
index 0d2b963..311ab5c 100644
--- a/pkgs/async/test/result/result_flattenAll_test.dart
+++ b/pkgs/async/test/result/result_flattenAll_test.dart
@@ -12,8 +12,10 @@
Result<T> err<T>(int n) => ErrorResult('$n', someStack);
/// Helper function creating an iterable of results.
-Iterable<Result<int>> results(int count,
- {bool Function(int index)? throwWhen}) sync* {
+Iterable<Result<int>> results(
+ int count, {
+ bool Function(int index)? throwWhen,
+}) sync* {
for (var i = 0; i < count; i++) {
if (throwWhen != null && throwWhen(i)) {
yield err(i);
@@ -41,17 +43,23 @@
});
test('single error', () {
expectAll(
- Result.flattenAll<int>(results(1, throwWhen: (_) => true)), err(0));
+ Result.flattenAll<int>(results(1, throwWhen: (_) => true)),
+ err(0),
+ );
});
test('multiple values', () {
expectAll(Result.flattenAll<int>(results(5)), res([0, 1, 2, 3, 4]));
});
test('multiple errors', () {
- expectAll(Result.flattenAll<int>(results(5, throwWhen: (x) => x.isOdd)),
- err(1)); // First error is result.
+ expectAll(
+ Result.flattenAll<int>(results(5, throwWhen: (x) => x.isOdd)),
+ err(1),
+ ); // First error is result.
});
test('error last', () {
expectAll(
- Result.flattenAll<int>(results(5, throwWhen: (x) => x == 4)), err(4));
+ Result.flattenAll<int>(results(5, throwWhen: (x) => x == 4)),
+ err(4),
+ );
});
}
diff --git a/pkgs/async/test/result/result_future_test.dart b/pkgs/async/test/result/result_future_test.dart
index de21884..a712e98 100644
--- a/pkgs/async/test/result/result_future_test.dart
+++ b/pkgs/async/test/result/result_future_test.dart
@@ -25,8 +25,10 @@
// The completer calls its listeners asynchronously. We have to wait
// before we can access the result.
- expect(future.then((_) => future.result!.asValue!.value),
- completion(equals(12)));
+ expect(
+ future.then((_) => future.result!.asValue!.value),
+ completion(equals(12)),
+ );
});
test("after an error completion, result is the future's error", () {
diff --git a/pkgs/async/test/result/result_test.dart b/pkgs/async/test/result/result_test.dart
index 9662046..65d47f9 100644
--- a/pkgs/async/test/result/result_test.dart
+++ b/pkgs/async/test/result/result_test.dart
@@ -59,11 +59,14 @@
test('complete with value', () {
Result<int> result = ValueResult<int>(42);
var c = Completer<int>();
- c.future.then(expectAsync1((int v) {
- expect(v, equals(42));
- }), onError: (Object? e, s) {
- fail('Unexpected error');
- });
+ c.future.then(
+ expectAsync1((int v) {
+ expect(v, equals(42));
+ }),
+ onError: (Object? e, s) {
+ fail('Unexpected error');
+ },
+ );
result.complete(c);
});
@@ -72,81 +75,103 @@
var c = Completer<bool>();
c.future.then((bool v) {
fail('Unexpected value $v');
- }).then<void>((_) {}, onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }));
+ }).then<void>(
+ (_) {},
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ );
result.complete(c);
});
test('add sink value', () {
var result = ValueResult<int>(42);
- EventSink<int> sink = TestSink(onData: expectAsync1((v) {
- expect(v, equals(42));
- }));
+ EventSink<int> sink = TestSink(
+ onData: expectAsync1((v) {
+ expect(v, equals(42));
+ }),
+ );
result.addTo(sink);
});
test('add sink error', () {
Result<bool> result = ErrorResult('BAD', stack);
- EventSink<bool> sink = TestSink(onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }));
+ EventSink<bool> sink = TestSink(
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ );
result.addTo(sink);
});
test('value as future', () {
Result<int> result = ValueResult<int>(42);
- result.asFuture.then(expectAsync1((int v) {
- expect(v, equals(42));
- }), onError: (Object? e, s) {
- fail('Unexpected error');
- });
+ result.asFuture.then(
+ expectAsync1((int v) {
+ expect(v, equals(42));
+ }),
+ onError: (Object? e, s) {
+ fail('Unexpected error');
+ },
+ );
});
test('error as future', () {
Result<bool> result = ErrorResult('BAD', stack);
result.asFuture.then((bool v) {
fail('Unexpected value $v');
- }).then<void>((_) {}, onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }));
+ }).then<void>(
+ (_) {},
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ );
});
test('capture future value', () {
var value = Future<int>.value(42);
- Result.capture(value).then(expectAsync1((Result result) {
- expect(result.isValue, isTrue);
- expect(result.isError, isFalse);
- var value = result.asValue!;
- expect(value.value, equals(42));
- }), onError: (Object? e, s) {
- fail('Unexpected error: $e');
- });
+ Result.capture(value).then(
+ expectAsync1((Result result) {
+ expect(result.isValue, isTrue);
+ expect(result.isError, isFalse);
+ var value = result.asValue!;
+ expect(value.value, equals(42));
+ }),
+ onError: (Object? e, s) {
+ fail('Unexpected error: $e');
+ },
+ );
});
test('capture future error', () {
var value = Future<bool>.error('BAD', stack);
- Result.capture(value).then(expectAsync1((Result result) {
- expect(result.isValue, isFalse);
- expect(result.isError, isTrue);
- var error = result.asError!;
- expect(error.error, equals('BAD'));
- expect(error.stackTrace, same(stack));
- }), onError: (Object? e, s) {
- fail('Unexpected error: $e');
- });
+ Result.capture(value).then(
+ expectAsync1((Result result) {
+ expect(result.isValue, isFalse);
+ expect(result.isError, isTrue);
+ var error = result.asError!;
+ expect(error.error, equals('BAD'));
+ expect(error.stackTrace, same(stack));
+ }),
+ onError: (Object? e, s) {
+ fail('Unexpected error: $e');
+ },
+ );
});
test('release future value', () {
var future = Future<Result<int>>.value(Result<int>.value(42));
- Result.release(future).then(expectAsync1((v) {
- expect(v, equals(42));
- }), onError: (Object? e, s) {
- fail('Unexpected error: $e');
- });
+ Result.release(future).then(
+ expectAsync1((v) {
+ expect(v, equals(42));
+ }),
+ onError: (Object? e, s) {
+ fail('Unexpected error: $e');
+ },
+ );
});
test('release future error', () {
@@ -154,10 +179,13 @@
var future = Future<Result<bool>>.value(Result<bool>.error('BAD', stack));
Result.release(future).then((v) {
fail('Unexpected value: $v');
- }).then<void>((_) {}, onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }));
+ }).then<void>(
+ (_) {},
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ );
});
test('release future real error', () {
@@ -165,24 +193,33 @@
var future = Future<Result<bool>>.error('BAD', stack);
Result.release(future).then((v) {
fail('Unexpected value: $v');
- }).then<void>((_) {}, onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }));
+ }).then<void>(
+ (_) {},
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ );
});
test('capture stream', () {
var c = StreamController<int>();
var stream = Result.captureStream(c.stream);
- var expectedList = Queue.of(
- [Result.value(42), Result.error('BAD', stack), Result.value(37)]);
+ var expectedList = Queue.of([
+ Result.value(42),
+ Result.error('BAD', stack),
+ Result.value(37),
+ ]);
void listener(Result actual) {
expect(expectedList.isEmpty, isFalse);
expectResult(actual, expectedList.removeFirst());
}
- stream.listen(expectAsync1(listener, count: 3),
- onDone: expectAsync0(() {}), cancelOnError: true);
+ stream.listen(
+ expectAsync1(listener, count: 3),
+ onDone: expectAsync0(() {}),
+ cancelOnError: true,
+ );
c.add(42);
c.addError('BAD', stack);
c.add(37);
@@ -195,7 +232,7 @@
var events = [
Result<int>.value(42),
Result<int>.error('BAD', stack),
- Result<int>.value(37)
+ Result<int>.value(37),
];
// Expect the data events, and an extra error event.
var expectedList = Queue.of(events)..add(Result.error('BAD2', stack));
@@ -215,9 +252,11 @@
expect(stackTrace, same(expected.asError!.stackTrace));
}
- stream.listen(expectAsync1(dataListener, count: 2),
- onError: expectAsync2(errorListener, count: 2),
- onDone: expectAsync0(() {}));
+ stream.listen(
+ expectAsync1(dataListener, count: 2),
+ onError: expectAsync2(errorListener, count: 2),
+ onDone: expectAsync0(() {}),
+ );
for (var result in events) {
c.add(result); // Result value or error in data line.
}
@@ -228,14 +267,19 @@
test('release stream cancel on error', () {
var c = StreamController<Result<int>>();
var stream = Result.releaseStream(c.stream);
- stream.listen(expectAsync1((v) {
- expect(v, equals(42));
- }), onError: expectAsync2((e, s) {
- expect(e, equals('BAD'));
- expect(s, same(stack));
- }), onDone: () {
- fail('Unexpected done event');
- }, cancelOnError: true);
+ stream.listen(
+ expectAsync1((v) {
+ expect(v, equals(42));
+ }),
+ onError: expectAsync2((e, s) {
+ expect(e, equals('BAD'));
+ expect(s, same(stack));
+ }),
+ onDone: () {
+ fail('Unexpected done event');
+ },
+ cancelOnError: true,
+ );
c.add(Result.value(42));
c.add(Result.error('BAD', stack));
c.add(Result.value(37));
@@ -318,16 +362,26 @@
test('handle neither unary nor binary', () {
var result = ErrorResult('error', stack);
expect(() => result.handle(() => fail('unreachable')), throwsA(anything));
- expect(() => result.handle((a, b, c) => fail('unreachable')),
- throwsA(anything));
- expect(() => result.handle((a, b, {c}) => fail('unreachable')),
- throwsA(anything));
- expect(() => result.handle((a, {b}) => fail('unreachable')),
- throwsA(anything));
- expect(() => result.handle(({a, b}) => fail('unreachable')),
- throwsA(anything));
expect(
- () => result.handle(({a}) => fail('unreachable')), throwsA(anything));
+ () => result.handle((a, b, c) => fail('unreachable')),
+ throwsA(anything),
+ );
+ expect(
+ () => result.handle((a, b, {c}) => fail('unreachable')),
+ throwsA(anything),
+ );
+ expect(
+ () => result.handle((a, {b}) => fail('unreachable')),
+ throwsA(anything),
+ );
+ expect(
+ () => result.handle(({a, b}) => fail('unreachable')),
+ throwsA(anything),
+ );
+ expect(
+ () => result.handle(({a}) => fail('unreachable')),
+ throwsA(anything),
+ );
});
}
@@ -347,10 +401,11 @@
final void Function(dynamic, StackTrace) onError;
final void Function() onDone;
- TestSink(
- {this.onData = _nullData,
- this.onError = _nullError,
- this.onDone = _nullDone});
+ TestSink({
+ this.onData = _nullData,
+ this.onError = _nullError,
+ this.onDone = _nullDone,
+ });
@override
void add(T value) {
diff --git a/pkgs/async/test/single_subscription_transformer_test.dart b/pkgs/async/test/single_subscription_transformer_test.dart
index 95b321b..9e4281c 100644
--- a/pkgs/async/test/single_subscription_transformer_test.dart
+++ b/pkgs/async/test/single_subscription_transformer_test.dart
@@ -12,8 +12,9 @@
void main() {
test("buffers events as soon as it's bound", () async {
var controller = StreamController.broadcast();
- var stream =
- controller.stream.transform(const SingleSubscriptionTransformer());
+ var stream = controller.stream.transform(
+ const SingleSubscriptionTransformer(),
+ );
// Add events before [stream] has a listener to be sure it buffers them.
controller.add(1);
@@ -28,23 +29,28 @@
controller.close();
});
- test("cancels the subscription to the broadcast stream when it's canceled",
- () async {
- var canceled = false;
- var controller = StreamController.broadcast(onCancel: () {
- canceled = true;
- });
- var stream =
- controller.stream.transform(const SingleSubscriptionTransformer());
- await flushMicrotasks();
- expect(canceled, isFalse);
+ test(
+ "cancels the subscription to the broadcast stream when it's canceled",
+ () async {
+ var canceled = false;
+ var controller = StreamController.broadcast(
+ onCancel: () {
+ canceled = true;
+ },
+ );
+ var stream = controller.stream.transform(
+ const SingleSubscriptionTransformer(),
+ );
+ await flushMicrotasks();
+ expect(canceled, isFalse);
- var subscription = stream.listen(null);
- await flushMicrotasks();
- expect(canceled, isFalse);
+ var subscription = stream.listen(null);
+ await flushMicrotasks();
+ expect(canceled, isFalse);
- subscription.cancel();
- await flushMicrotasks();
- expect(canceled, isTrue);
- });
+ subscription.cancel();
+ await flushMicrotasks();
+ expect(canceled, isTrue);
+ },
+ );
}
diff --git a/pkgs/async/test/sink_base_test.dart b/pkgs/async/test/sink_base_test.dart
index ee324f5..96e801c 100644
--- a/pkgs/async/test/sink_base_test.dart
+++ b/pkgs/async/test/sink_base_test.dart
@@ -18,29 +18,34 @@
// implementation with [StreamSinkBase].
group('StreamSinkBase', () {
test('forwards add() to onAdd()', () {
- var sink = _StreamSink(onAdd: expectAsync1((value) {
- expect(value, equals(123));
- }));
+ var sink = _StreamSink(
+ onAdd: expectAsync1((value) {
+ expect(value, equals(123));
+ }),
+ );
sink.add(123);
});
test('forwards addError() to onError()', () {
- var sink = _StreamSink(onError: expectAsync2((error, [stackTrace]) {
- expect(error, equals('oh no'));
- expect(stackTrace, isA<StackTrace>());
- }));
+ var sink = _StreamSink(
+ onError: expectAsync2((error, [stackTrace]) {
+ expect(error, equals('oh no'));
+ expect(stackTrace, isA<StackTrace>());
+ }),
+ );
sink.addError('oh no', StackTrace.current);
});
test('forwards addStream() to onAdd() and onError()', () {
var sink = _StreamSink(
- onAdd: expectAsync1((value) {
- expect(value, equals(123));
- }, count: 1),
- onError: expectAsync2((error, [stackTrace]) {
- expect(error, equals('oh no'));
- expect(stackTrace, isA<StackTrace>());
- }));
+ onAdd: expectAsync1((value) {
+ expect(value, equals(123));
+ }, count: 1),
+ onError: expectAsync2((error, [stackTrace]) {
+ expect(error, equals('oh no'));
+ expect(stackTrace, isA<StackTrace>());
+ }),
+ );
var controller = StreamController<int>();
sink.addStream(controller.stream);
@@ -104,25 +109,27 @@
expect(doneCompleted, isTrue);
});
- test('done returns a future that completes once close() completes',
- () async {
- var completer = Completer<void>();
- var sink = _StreamSink(onClose: expectAsync0(() => completer.future));
+ test(
+ 'done returns a future that completes once close() completes',
+ () async {
+ var completer = Completer<void>();
+ var sink = _StreamSink(onClose: expectAsync0(() => completer.future));
- var doneCompleted = false;
- sink.done.then((_) => doneCompleted = true);
+ var doneCompleted = false;
+ sink.done.then((_) => doneCompleted = true);
- await pumpEventQueue();
- expect(doneCompleted, isFalse);
+ await pumpEventQueue();
+ expect(doneCompleted, isFalse);
- expect(sink.close(), completes);
- await pumpEventQueue();
- expect(doneCompleted, isFalse);
+ expect(sink.close(), completes);
+ await pumpEventQueue();
+ expect(doneCompleted, isFalse);
- completer.complete();
- await pumpEventQueue();
- expect(doneCompleted, isTrue);
- });
+ completer.complete();
+ await pumpEventQueue();
+ expect(doneCompleted, isTrue);
+ },
+ );
group('during addStream()', () {
test('add() throws an error', () {
@@ -179,25 +186,30 @@
});
test('converts the text to data and passes it to add', () async {
- var sink = _IOSink(onAdd: expectAsync1((data) {
- expect(data, equals(utf8.encode('hello')));
- }));
+ var sink = _IOSink(
+ onAdd: expectAsync1((data) {
+ expect(data, equals(utf8.encode('hello')));
+ }),
+ );
sink.write('hello');
});
test('calls Object.toString()', () async {
- var sink = _IOSink(onAdd: expectAsync1((data) {
- expect(data, equals(utf8.encode('123')));
- }));
+ var sink = _IOSink(
+ onAdd: expectAsync1((data) {
+ expect(data, equals(utf8.encode('123')));
+ }),
+ );
sink.write(123);
});
test('respects the encoding', () async {
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- expect(data, equals(latin1.encode('Æ')));
- }),
- encoding: latin1);
+ onAdd: expectAsync1((data) {
+ expect(data, equals(latin1.encode('Æ')));
+ }),
+ encoding: latin1,
+ );
sink.write('Æ');
});
@@ -217,9 +229,10 @@
test('writes each object in the iterable', () async {
var chunks = <List<int>>[];
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- chunks.add(data);
- }, count: 3));
+ onAdd: expectAsync1((data) {
+ chunks.add(data);
+ }, count: 3),
+ );
sink.writeAll(['hello', null, 123]);
expect(chunks, equals(['hello', 'null', '123'].map(utf8.encode)));
@@ -228,13 +241,16 @@
test('writes separators between each object', () async {
var chunks = <List<int>>[];
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- chunks.add(data);
- }, count: 5));
+ onAdd: expectAsync1((data) {
+ chunks.add(data);
+ }, count: 5),
+ );
sink.writeAll(['hello', null, 123], '/');
- expect(chunks,
- equals(['hello', '/', 'null', '/', '123'].map(utf8.encode)));
+ expect(
+ chunks,
+ equals(['hello', '/', 'null', '/', '123'].map(utf8.encode)),
+ );
});
test('throws if the sink is closed', () async {
@@ -247,18 +263,20 @@
group('writeln()', () {
test('only writes a newline by default', () async {
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- expect(data, equals(utf8.encode('\n')));
- }, count: 1));
+ onAdd: expectAsync1((data) {
+ expect(data, equals(utf8.encode('\n')));
+ }, count: 1),
+ );
sink.writeln();
});
test('writes the object followed by a newline', () async {
var chunks = <List<int>>[];
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- chunks.add(data);
- }, count: 2));
+ onAdd: expectAsync1((data) {
+ chunks.add(data);
+ }, count: 2),
+ );
sink.writeln(123);
expect(chunks, equals(['123', '\n'].map(utf8.encode)));
@@ -273,18 +291,21 @@
group('writeCharCode()', () {
test('writes the character code', () async {
- var sink = _IOSink(onAdd: expectAsync1((data) {
- expect(data, equals(utf8.encode('A')));
- }));
+ var sink = _IOSink(
+ onAdd: expectAsync1((data) {
+ expect(data, equals(utf8.encode('A')));
+ }),
+ );
sink.writeCharCode(letterA);
});
test('respects the encoding', () async {
var sink = _IOSink(
- onAdd: expectAsync1((data) {
- expect(data, equals(latin1.encode('Æ')));
- }),
- encoding: latin1);
+ onAdd: expectAsync1((data) {
+ expect(data, equals(latin1.encode('Æ')));
+ }),
+ encoding: latin1,
+ );
sink.writeCharCode('Æ'.runes.first);
});
@@ -324,8 +345,9 @@
});
test('locks the sink as though a stream was being added', () {
- var sink =
- _IOSink(onFlush: expectAsync0(() => Completer<void>().future));
+ var sink = _IOSink(
+ onFlush: expectAsync0(() => Completer<void>().future),
+ );
sink.flush();
expect(() => sink.add([0]), throwsStateError);
expect(() => sink.addError('oh no'), throwsStateError);
@@ -344,11 +366,11 @@
final void Function(Object error, [StackTrace? stackTrace]) _onError;
final FutureOr<void> Function() _onClose;
- _StreamSink(
- {void Function(int value)? onAdd,
- void Function(Object error, [StackTrace? stackTrace])? onError,
- FutureOr<void> Function()? onClose})
- : _onAdd = onAdd ?? ((_) {}),
+ _StreamSink({
+ void Function(int value)? onAdd,
+ void Function(Object error, [StackTrace? stackTrace])? onError,
+ FutureOr<void> Function()? onClose,
+ }) : _onAdd = onAdd ?? ((_) {}),
_onError = onError ?? ((_, [__]) {}),
_onClose = onClose ?? (() {});
@@ -374,13 +396,13 @@
final FutureOr<void> Function() _onClose;
final Future<void> Function() _onFlush;
- _IOSink(
- {void Function(List<int> value)? onAdd,
- void Function(Object error, [StackTrace? stackTrace])? onError,
- FutureOr<void> Function()? onClose,
- Future<void> Function()? onFlush,
- Encoding encoding = utf8})
- : _onAdd = onAdd ?? ((_) {}),
+ _IOSink({
+ void Function(List<int> value)? onAdd,
+ void Function(Object error, [StackTrace? stackTrace])? onError,
+ FutureOr<void> Function()? onClose,
+ Future<void> Function()? onFlush,
+ Encoding encoding = utf8,
+ }) : _onAdd = onAdd ?? ((_) {}),
_onError = onError ?? ((_, [__]) {}),
_onClose = onClose ?? (() {}),
_onFlush = onFlush ?? Future.value,
diff --git a/pkgs/async/test/stream_closer_test.dart b/pkgs/async/test/stream_closer_test.dart
index a2bad1a..3f6fa26 100644
--- a/pkgs/async/test/stream_closer_test.dart
+++ b/pkgs/async/test/stream_closer_test.dart
@@ -18,12 +18,16 @@
group('when the closer is never closed', () {
test('forwards data and done events', () {
expect(
- createStream().transform(closer).toList(), completion([1, 2, 3, 4]));
+ createStream().transform(closer).toList(),
+ completion([1, 2, 3, 4]),
+ );
});
test('forwards error events', () {
- expect(Stream<int>.error('oh no').transform(closer).toList(),
- throwsA('oh no'));
+ expect(
+ Stream<int>.error('oh no').transform(closer).toList(),
+ throwsA('oh no'),
+ );
});
test('transforms a broadcast stream into a broadcast stream', () {
@@ -53,8 +57,9 @@
test('forwards cancel', () {
var isCancelled = false;
- var controller =
- StreamController<int>(onCancel: () => isCancelled = true);
+ var controller = StreamController<int>(
+ onCancel: () => isCancelled = true,
+ );
var transformed = controller.stream.transform(closer);
expect(isCancelled, isFalse);
@@ -67,8 +72,10 @@
test('forwards errors from cancel', () {
var controller = StreamController<int>(onCancel: () => throw 'oh no');
- expect(controller.stream.transform(closer).listen(null).cancel(),
- throwsA('oh no'));
+ expect(
+ controller.stream.transform(closer).listen(null).cancel(),
+ throwsA('oh no'),
+ );
});
});
@@ -83,8 +90,9 @@
test('the inner subscription is canceled once the closer is closed', () {
var isCancelled = false;
- var controller =
- StreamController<int>(onCancel: () => isCancelled = true);
+ var controller = StreamController<int>(
+ onCancel: () => isCancelled = true,
+ );
expect(controller.stream.transform(closer), emitsDone);
expect(closer.close(), completes);
@@ -98,18 +106,24 @@
expect(closer.close(), throwsA('oh no'));
});
- test('closer.close() works even if a stream has already completed',
- () async {
- expect(await createStream().transform(closer).toList(),
- equals([1, 2, 3, 4]));
- expect(closer.close(), completes);
- });
+ test(
+ 'closer.close() works even if a stream has already completed',
+ () async {
+ expect(
+ await createStream().transform(closer).toList(),
+ equals([1, 2, 3, 4]),
+ );
+ expect(closer.close(), completes);
+ },
+ );
- test('closer.close() works even if a stream has already been canceled',
- () async {
- createStream().transform(closer).listen(null).cancel();
- expect(closer.close(), completes);
- });
+ test(
+ 'closer.close() works even if a stream has already been canceled',
+ () async {
+ createStream().transform(closer).listen(null).cancel();
+ expect(closer.close(), completes);
+ },
+ );
group('but listened afterwards', () {
test('the output stream immediately emits done', () {
@@ -121,8 +135,9 @@
test(
'the underlying subscription is never listened if the stream is '
'never listened', () async {
- var controller =
- StreamController<int>(onListen: expectAsync0(() {}, count: 0));
+ var controller = StreamController<int>(
+ onListen: expectAsync0(() {}, count: 0),
+ );
controller.stream.transform(closer);
expect(closer.close(), completes);
@@ -134,7 +149,9 @@
'the underlying subscription is listened and then canceled once the '
'stream is listened', () {
var controller = StreamController<int>(
- onListen: expectAsync0(() {}), onCancel: expectAsync0(() {}));
+ onListen: expectAsync0(() {}),
+ onCancel: expectAsync0(() {}),
+ );
var stream = controller.stream.transform(closer);
expect(closer.close(), completes);
@@ -143,8 +160,9 @@
});
test('Subscription.cancel() errors are silently ignored', () async {
- var controller =
- StreamController<int>(onCancel: expectAsync0(() => throw 'oh no'));
+ var controller = StreamController<int>(
+ onCancel: expectAsync0(() => throw 'oh no'),
+ );
var stream = controller.stream.transform(closer);
expect(closer.close(), completes);
@@ -166,8 +184,9 @@
'listened', () async {
expect(closer.close(), completes);
- var controller =
- StreamController<int>(onListen: expectAsync0(() {}, count: 0));
+ var controller = StreamController<int>(
+ onListen: expectAsync0(() {}, count: 0),
+ );
controller.stream.transform(closer);
await pumpEventQueue();
@@ -179,7 +198,9 @@
expect(closer.close(), completes);
var controller = StreamController<int>(
- onListen: expectAsync0(() {}), onCancel: expectAsync0(() {}));
+ onListen: expectAsync0(() {}),
+ onCancel: expectAsync0(() {}),
+ );
controller.stream.transform(closer).listen(null);
});
@@ -187,8 +208,9 @@
test('Subscription.cancel() errors are silently ignored', () async {
expect(closer.close(), completes);
- var controller =
- StreamController<int>(onCancel: expectAsync0(() => throw 'oh no'));
+ var controller = StreamController<int>(
+ onCancel: expectAsync0(() => throw 'oh no'),
+ );
controller.stream.transform(closer).listen(null);
diff --git a/pkgs/async/test/stream_completer_test.dart b/pkgs/async/test/stream_completer_test.dart
index f58162e..0ef5cf4 100644
--- a/pkgs/async/test/stream_completer_test.dart
+++ b/pkgs/async/test/stream_completer_test.dart
@@ -82,16 +82,18 @@
var lastEvent = -1;
var controller = StreamController<int>();
late StreamSubscription subscription;
- subscription = completer.stream.listen((value) {
- expect(value, lessThan(3));
- lastEvent = value;
- if (value == 2) {
- subscription.cancel();
- }
- },
- onError: unreachable('error'),
- onDone: unreachable('done'),
- cancelOnError: true);
+ subscription = completer.stream.listen(
+ (value) {
+ expect(value, lessThan(3));
+ lastEvent = value;
+ if (value == 2) {
+ subscription.cancel();
+ }
+ },
+ onError: unreachable('error'),
+ onDone: unreachable('done'),
+ cancelOnError: true,
+ );
completer.setSourceStream(controller.stream);
expect(controller.hasListener, isTrue);
@@ -113,16 +115,22 @@
var completer = StreamCompleter<void>();
completer.setEmpty();
var done = Completer<void>();
- completer.stream.listen(unreachable('data'),
- onError: unreachable('error'), onDone: done.complete);
+ completer.stream.listen(
+ unreachable('data'),
+ onError: unreachable('error'),
+ onDone: done.complete,
+ );
await done.future;
});
test('complete with setEmpty after listening', () async {
var completer = StreamCompleter<void>();
var done = Completer<void>();
- completer.stream.listen(unreachable('data'),
- onError: unreachable('error'), onDone: done.complete);
+ completer.stream.listen(
+ unreachable('data'),
+ onError: unreachable('error'),
+ onDone: done.complete,
+ );
completer.setEmpty();
await done.future;
});
@@ -130,9 +138,11 @@
test("source stream isn't listened to until completer stream is", () async {
var completer = StreamCompleter<void>();
late StreamController controller;
- controller = StreamController(onListen: () {
- scheduleMicrotask(controller.close);
- });
+ controller = StreamController(
+ onListen: () {
+ scheduleMicrotask(controller.close);
+ },
+ );
completer.setSourceStream(controller.stream);
await flushMicrotasks();
@@ -146,13 +156,18 @@
var completer = StreamCompleter<Object>();
Object lastEvent = -1;
var controller = StreamController<Object>();
- completer.stream.listen((value) {
- expect(value, lessThan(3));
- lastEvent = value;
- }, onError: (Object value) {
- expect(value, '3');
- lastEvent = value;
- }, onDone: unreachable('done'), cancelOnError: true);
+ completer.stream.listen(
+ (value) {
+ expect(value, lessThan(3));
+ lastEvent = value;
+ },
+ onError: (Object value) {
+ expect(value, '3');
+ lastEvent = value;
+ },
+ onDone: unreachable('done'),
+ cancelOnError: true,
+ );
completer.setSourceStream(controller.stream);
expect(controller.hasListener, isTrue);
@@ -183,13 +198,18 @@
controller.add(1);
expect(controller.hasListener, isFalse);
- completer.stream.listen((value) {
- expect(value, lessThan(3));
- lastEvent = value;
- }, onError: (Object value) {
- expect(value, '3');
- lastEvent = value;
- }, onDone: unreachable('done'), cancelOnError: true);
+ completer.stream.listen(
+ (value) {
+ expect(value, lessThan(3));
+ lastEvent = value;
+ },
+ onError: (Object value) {
+ expect(value, '3');
+ lastEvent = value;
+ },
+ onDone: unreachable('done'),
+ cancelOnError: true,
+ );
expect(controller.hasListener, isTrue);
@@ -315,42 +335,55 @@
test('asFuture with error accross setting stream', () async {
var completer = StreamCompleter<void>();
var controller = StreamController<void>();
- var subscription =
- completer.stream.listen(unreachable('data'), cancelOnError: false);
+ var subscription = completer.stream.listen(
+ unreachable('data'),
+ cancelOnError: false,
+ );
var done = subscription.asFuture();
expect(controller.hasListener, isFalse);
completer.setSourceStream(controller.stream);
await flushMicrotasks();
expect(controller.hasListener, isTrue);
controller.addError(42);
- await done.then(unreachable('data'), onError: (Object error) {
- expect(error, 42);
- });
+ await done.then(
+ unreachable('data'),
+ onError: (Object error) {
+ expect(error, 42);
+ },
+ );
expect(controller.hasListener, isFalse);
});
group('setError()', () {
test('produces a stream that emits a single error', () {
var completer = StreamCompleter<void>();
- completer.stream.listen(unreachable('data'),
- onError: expectAsync2((error, stackTrace) {
- expect(error, equals('oh no'));
- }), onDone: expectAsync0(() {}));
+ completer.stream.listen(
+ unreachable('data'),
+ onError: expectAsync2((error, stackTrace) {
+ expect(error, equals('oh no'));
+ }),
+ onDone: expectAsync0(() {}),
+ );
completer.setError('oh no');
});
- test('produces a stream that emits a single error on a later listen',
- () async {
- var completer = StreamCompleter<void>();
- completer.setError('oh no');
- await flushMicrotasks();
+ test(
+ 'produces a stream that emits a single error on a later listen',
+ () async {
+ var completer = StreamCompleter<void>();
+ completer.setError('oh no');
+ await flushMicrotasks();
- completer.stream.listen(unreachable('data'),
+ completer.stream.listen(
+ unreachable('data'),
onError: expectAsync2((error, stackTrace) {
- expect(error, equals('oh no'));
- }), onDone: expectAsync0(() {}));
- });
+ expect(error, equals('oh no'));
+ }),
+ onDone: expectAsync0(() {}),
+ );
+ },
+ );
});
}
diff --git a/pkgs/async/test/stream_extensions_test.dart b/pkgs/async/test/stream_extensions_test.dart
index b43dedc..050732f 100644
--- a/pkgs/async/test/stream_extensions_test.dart
+++ b/pkgs/async/test/stream_extensions_test.dart
@@ -15,36 +15,48 @@
test('with the same length as the iterable', () {
expect(
- Stream.fromIterable([1, 2, 3]).slices(3).toList(),
- completion(equals([
- [1, 2, 3]
- ])));
+ Stream.fromIterable([1, 2, 3]).slices(3).toList(),
+ completion(
+ equals([
+ [1, 2, 3],
+ ]),
+ ),
+ );
});
test('with a longer length than the iterable', () {
expect(
- Stream.fromIterable([1, 2, 3]).slices(5).toList(),
- completion(equals([
- [1, 2, 3]
- ])));
+ Stream.fromIterable([1, 2, 3]).slices(5).toList(),
+ completion(
+ equals([
+ [1, 2, 3],
+ ]),
+ ),
+ );
});
test('with a shorter length than the iterable', () {
expect(
- Stream.fromIterable([1, 2, 3]).slices(2).toList(),
- completion(equals([
+ Stream.fromIterable([1, 2, 3]).slices(2).toList(),
+ completion(
+ equals([
[1, 2],
- [3]
- ])));
+ [3],
+ ]),
+ ),
+ );
});
test('with length divisible by the iterable\'s', () {
expect(
- Stream.fromIterable([1, 2, 3, 4]).slices(2).toList(),
- completion(equals([
+ Stream.fromIterable([1, 2, 3, 4]).slices(2).toList(),
+ completion(
+ equals([
[1, 2],
- [3, 4]
- ])));
+ [3, 4],
+ ]),
+ ),
+ );
});
test('refuses negative length', () {
@@ -59,7 +71,9 @@
group('.firstOrNull', () {
test('returns the first data event', () {
expect(
- Stream.fromIterable([1, 2, 3, 4]).firstOrNull, completion(equals(1)));
+ Stream.fromIterable([1, 2, 3, 4]).firstOrNull,
+ completion(equals(1)),
+ );
});
test('returns the first error event', () {
@@ -72,9 +86,11 @@
test('cancels the subscription after an event', () async {
var isCancelled = false;
- var controller = StreamController<int>(onCancel: () {
- isCancelled = true;
- });
+ var controller = StreamController<int>(
+ onCancel: () {
+ isCancelled = true;
+ },
+ );
controller.add(1);
await expectLater(controller.stream.firstOrNull, completion(equals(1)));
@@ -83,9 +99,11 @@
test('cancels the subscription after an error', () async {
var isCancelled = false;
- var controller = StreamController<int>(onCancel: () {
- isCancelled = true;
- });
+ var controller = StreamController<int>(
+ onCancel: () {
+ isCancelled = true;
+ },
+ );
controller.addError('oh no');
await expectLater(controller.stream.firstOrNull, throwsA('oh no'));
@@ -119,28 +137,32 @@
..close();
});
- test('emits events added before and after the listenAndBuffer is listened',
- () async {
- var controller = StreamController<int>()
- ..add(1)
- ..add(2)
- ..add(3);
- var stream = controller.stream.listenAndBuffer();
- expectLater(stream, emitsInOrder([1, 2, 3, 4, 5, 6, emitsDone]));
- await pumpEventQueue();
+ test(
+ 'emits events added before and after the listenAndBuffer is listened',
+ () async {
+ var controller = StreamController<int>()
+ ..add(1)
+ ..add(2)
+ ..add(3);
+ var stream = controller.stream.listenAndBuffer();
+ expectLater(stream, emitsInOrder([1, 2, 3, 4, 5, 6, emitsDone]));
+ await pumpEventQueue();
- controller
- ..add(4)
- ..add(5)
- ..add(6)
- ..close();
- });
+ controller
+ ..add(4)
+ ..add(5)
+ ..add(6)
+ ..close();
+ },
+ );
test('listens as soon as listenAndBuffer() is called', () async {
var listened = false;
- var controller = StreamController<int>(onListen: () {
- listened = true;
- });
+ var controller = StreamController<int>(
+ onListen: () {
+ listened = true;
+ },
+ );
controller.stream.listenAndBuffer();
expect(listened, isTrue);
});
@@ -160,10 +182,12 @@
test('forwards cancel', () async {
var completer = Completer<void>();
var canceled = false;
- var controller = StreamController<int>(onCancel: () {
- canceled = true;
- return completer.future;
- });
+ var controller = StreamController<int>(
+ onCancel: () {
+ canceled = true;
+ return completer.future;
+ },
+ );
var stream = controller.stream.listenAndBuffer();
expect(canceled, isFalse);
var subscription = stream.listen(null);
diff --git a/pkgs/async/test/stream_group_test.dart b/pkgs/async/test/stream_group_test.dart
index 7b40f6e..ac09e95 100644
--- a/pkgs/async/test/stream_group_test.dart
+++ b/pkgs/async/test/stream_group_test.dart
@@ -29,8 +29,10 @@
expect(streamGroup.close(), completes);
- expect(streamGroup.stream.toList(),
- completion(unorderedEquals(['first', 'second'])));
+ expect(
+ streamGroup.stream.toList(),
+ completion(unorderedEquals(['first', 'second'])),
+ );
});
test('buffers errors from multiple sources', () async {
@@ -49,10 +51,14 @@
expect(streamGroup.close(), completes);
var transformed = streamGroup.stream.transform(
- StreamTransformer<String, String>.fromHandlers(
- handleError: (error, _, sink) => sink.add('error: $error')));
- expect(transformed.toList(),
- completion(equals(['error: first', 'error: second'])));
+ StreamTransformer<String, String>.fromHandlers(
+ handleError: (error, _, sink) => sink.add('error: $error'),
+ ),
+ );
+ expect(
+ transformed.toList(),
+ completion(equals(['error: first', 'error: second'])),
+ );
});
test('buffers events and errors together', () async {
@@ -72,19 +78,24 @@
expect(streamGroup.close(), completes);
var transformed = streamGroup.stream.transform(
- StreamTransformer<String, String>.fromHandlers(
- handleData: (data, sink) => sink.add('data: $data'),
- handleError: (error, _, sink) => sink.add('error: $error')));
+ StreamTransformer<String, String>.fromHandlers(
+ handleData: (data, sink) => sink.add('data: $data'),
+ handleError: (error, _, sink) => sink.add('error: $error'),
+ ),
+ );
expect(
- transformed.toList(),
- completion(equals([
+ transformed.toList(),
+ completion(
+ equals([
'data: first',
'error: second',
'data: third',
'error: fourth',
'error: fifth',
- 'data: sixth'
- ])));
+ 'data: sixth',
+ ]),
+ ),
+ );
});
test("emits events once there's a listener", () {
@@ -92,7 +103,9 @@
streamGroup.add(controller.stream);
expect(
- streamGroup.stream.toList(), completion(equals(['first', 'second'])));
+ streamGroup.stream.toList(),
+ completion(equals(['first', 'second'])),
+ );
controller.add('first');
controller.add('second');
@@ -140,7 +153,9 @@
streamGroup.add(controller.stream);
expect(
- streamGroup.stream.toList(), completion(equals(['first', 'second'])));
+ streamGroup.stream.toList(),
+ completion(equals(['first', 'second'])),
+ );
controller.add('first');
controller.add('second');
@@ -163,8 +178,9 @@
var subscription = streamGroup.stream.listen(null);
var completer = Completer<void>();
- var controller =
- StreamController<String>(onCancel: () => completer.future);
+ var controller = StreamController<String>(
+ onCancel: () => completer.future,
+ );
streamGroup.add(controller.stream);
await flushMicrotasks();
@@ -187,7 +203,9 @@
var paused = false;
var controller = StreamController<String>(
- onPause: () => paused = true, onResume: () => paused = false);
+ onPause: () => paused = true,
+ onResume: () => paused = false,
+ );
subscription.pause();
await flushMicrotasks();
@@ -210,12 +228,15 @@
test('immediately listens to and cancels the stream', () async {
var listened = false;
var canceled = false;
- var controller = StreamController<String>(onListen: () {
- listened = true;
- }, onCancel: expectAsync0(() {
- expect(listened, isTrue);
- canceled = true;
- }));
+ var controller = StreamController<String>(
+ onListen: () {
+ listened = true;
+ },
+ onCancel: expectAsync0(() {
+ expect(listened, isTrue);
+ canceled = true;
+ }),
+ );
streamGroup.add(controller.stream);
await flushMicrotasks();
@@ -224,16 +245,18 @@
});
test('forwards cancel errors', () {
- var controller =
- StreamController<String>(onCancel: () => throw 'error');
+ var controller = StreamController<String>(
+ onCancel: () => throw 'error',
+ );
expect(streamGroup.add(controller.stream), throwsA('error'));
});
test('forwards a cancel future', () async {
var completer = Completer<void>();
- var controller =
- StreamController<String>(onCancel: () => completer.future);
+ var controller = StreamController<String>(
+ onCancel: () => completer.future,
+ );
var fired = false;
streamGroup.add(controller.stream)!.then((_) => fired = true);
@@ -260,21 +283,24 @@
// We can't use expect(..., throwsStateError) here bceause of
// dart-lang/sdk#45815.
runZonedGuarded(
- () => streamGroup.stream.listen(expectAsync1((_) {}, count: 0)),
- expectAsync2((error, _) => expect(error, isStateError)));
+ () => streamGroup.stream.listen(expectAsync1((_) {}, count: 0)),
+ expectAsync2((error, _) => expect(error, isStateError)),
+ );
});
test('cancels other subscriptions', () async {
var firstCancelled = false;
- var first =
- StreamController<String>(onCancel: () => firstCancelled = true);
+ var first = StreamController<String>(
+ onCancel: () => firstCancelled = true,
+ );
streamGroup.add(first.stream);
streamGroup.add(alreadyListened);
var lastCancelled = false;
- var last =
- StreamController<String>(onCancel: () => lastCancelled = true);
+ var last = StreamController<String>(
+ onCancel: () => lastCancelled = true,
+ );
streamGroup.add(last.stream);
runZonedGuarded(() => streamGroup.stream.listen(null), (_, __) {});
@@ -290,8 +316,9 @@
streamGroup.add(alreadyListened);
var subscription = runZonedGuarded(
- () => streamGroup.stream.listen(null),
- expectAsync2((_, __) {}, count: 1));
+ () => streamGroup.stream.listen(null),
+ expectAsync2((_, __) {}, count: 1),
+ );
expect(subscription!.cancel(), completes);
});
@@ -300,8 +327,9 @@
streamGroup.add(alreadyListened);
var subscription = runZonedGuarded(
- () => streamGroup.stream.listen(null),
- expectAsync2((_, __) {}, count: 1));
+ () => streamGroup.stream.listen(null),
+ expectAsync2((_, __) {}, count: 1),
+ );
await pumpEventQueue();
expect(subscription!.cancel(), completes);
@@ -333,7 +361,9 @@
expect(streamGroup.close(), completes);
expect(
- streamGroup.stream.toList(), completion(equals(['first', 'second'])));
+ streamGroup.stream.toList(),
+ completion(equals(['first', 'second'])),
+ );
});
test("emits events from multiple sources once there's a listener", () {
@@ -344,7 +374,9 @@
streamGroup.add(controller2.stream);
expect(
- streamGroup.stream.toList(), completion(equals(['first', 'second'])));
+ streamGroup.stream.toList(),
+ completion(equals(['first', 'second'])),
+ );
controller1.add('first');
controller2.add('second');
@@ -354,23 +386,25 @@
expect(streamGroup.close(), completes);
});
- test("doesn't buffer events once a listener has been added and removed",
- () async {
- var controller = StreamController<String>();
- streamGroup.add(controller.stream);
+ test(
+ "doesn't buffer events once a listener has been added and removed",
+ () async {
+ var controller = StreamController<String>();
+ streamGroup.add(controller.stream);
- streamGroup.stream.listen(null).cancel();
- await flushMicrotasks();
+ streamGroup.stream.listen(null).cancel();
+ await flushMicrotasks();
- controller.add('first');
- controller.addError('second');
- controller.close();
+ controller.add('first');
+ controller.addError('second');
+ controller.close();
- await flushMicrotasks();
+ await flushMicrotasks();
- expect(streamGroup.close(), completes);
- expect(streamGroup.stream.toList(), completion(isEmpty));
- });
+ expect(streamGroup.close(), completes);
+ expect(streamGroup.stream.toList(), completion(isEmpty));
+ },
+ );
test("doesn't buffer events from a broadcast stream", () async {
var controller = StreamController<String>.broadcast();
@@ -390,7 +424,9 @@
streamGroup.add(controller.stream);
expect(
- streamGroup.stream.toList(), completion(equals(['first', 'second'])));
+ streamGroup.stream.toList(),
+ completion(equals(['first', 'second'])),
+ );
controller.add('first');
controller.add('second');
@@ -438,8 +474,9 @@
test('never cancels single-subscription streams', () async {
var subscription = streamGroup.stream.listen(null);
- var controller =
- StreamController<String>(onCancel: expectAsync0(() {}, count: 0));
+ var controller = StreamController<String>(
+ onCancel: expectAsync0(() {}, count: 0),
+ );
streamGroup.add(controller.stream);
await flushMicrotasks();
@@ -451,29 +488,31 @@
await flushMicrotasks();
});
- test('drops events from a single-subscription stream while dormant',
- () async {
- var events = [];
- var subscription = streamGroup.stream.listen(events.add);
+ test(
+ 'drops events from a single-subscription stream while dormant',
+ () async {
+ var events = [];
+ var subscription = streamGroup.stream.listen(events.add);
- var controller = StreamController<String>();
- streamGroup.add(controller.stream);
- await flushMicrotasks();
+ var controller = StreamController<String>();
+ streamGroup.add(controller.stream);
+ await flushMicrotasks();
- controller.add('first');
- await flushMicrotasks();
- expect(events, equals(['first']));
+ controller.add('first');
+ await flushMicrotasks();
+ expect(events, equals(['first']));
- subscription.cancel();
- controller.add('second');
- await flushMicrotasks();
- expect(events, equals(['first']));
+ subscription.cancel();
+ controller.add('second');
+ await flushMicrotasks();
+ expect(events, equals(['first']));
- streamGroup.stream.listen(events.add);
- controller.add('third');
- await flushMicrotasks();
- expect(events, equals(['first', 'third']));
- });
+ streamGroup.stream.listen(events.add);
+ controller.add('third');
+ await flushMicrotasks();
+ expect(events, equals(['first', 'third']));
+ },
+ );
test('a single-subscription stream can be removed while dormant', () async {
var controller = StreamController<String>();
@@ -492,21 +531,23 @@
expect(streamGroup.close(), completes);
});
- test('completes close() when streams close without being removed',
- () async {
- var controller = StreamController.broadcast();
- var group = StreamGroup.broadcast();
- group.add(controller.stream);
- var closeCompleted = false;
- group.close().then((_) => closeCompleted = true);
+ test(
+ 'completes close() when streams close without being removed',
+ () async {
+ var controller = StreamController.broadcast();
+ var group = StreamGroup.broadcast();
+ group.add(controller.stream);
+ var closeCompleted = false;
+ group.close().then((_) => closeCompleted = true);
- await flushMicrotasks();
- expect(closeCompleted, isFalse);
+ await flushMicrotasks();
+ expect(closeCompleted, isFalse);
- await controller.close();
- await flushMicrotasks();
- expect(closeCompleted, isTrue);
- });
+ await controller.close();
+ await flushMicrotasks();
+ expect(closeCompleted, isTrue);
+ },
+ );
});
group('regardless of type', () {
@@ -537,8 +578,10 @@
var controller1 = StreamController<String>();
var controller2 = StreamController<String>();
- var merged =
- StreamGroup.mergeBroadcast([controller1.stream, controller2.stream]);
+ var merged = StreamGroup.mergeBroadcast([
+ controller1.stream,
+ controller2.stream,
+ ]);
controller1.add('first');
controller1.close();
@@ -559,18 +602,20 @@
group('add()', () {
group('while dormant', () {
- test("doesn't listen to the stream until the group is listened to",
- () async {
- var controller = StreamController<String>();
+ test(
+ "doesn't listen to the stream until the group is listened to",
+ () async {
+ var controller = StreamController<String>();
- expect(streamGroup.add(controller.stream), isNull);
- await flushMicrotasks();
- expect(controller.hasListener, isFalse);
+ expect(streamGroup.add(controller.stream), isNull);
+ await flushMicrotasks();
+ expect(controller.hasListener, isFalse);
- streamGroup.stream.listen(null);
- await flushMicrotasks();
- expect(controller.hasListener, isTrue);
- });
+ streamGroup.stream.listen(null);
+ await flushMicrotasks();
+ expect(controller.hasListener, isTrue);
+ },
+ );
test('is a no-op if the stream is already in the group', () {
var controller = StreamController<String>();
@@ -631,27 +676,29 @@
expect(streamGroup.remove(controller.stream), isNull);
});
- test('and closed closes the group when the last stream is removed',
- () async {
- var controller1 = StreamController<String>();
- var controller2 = StreamController<String>();
+ test(
+ 'and closed closes the group when the last stream is removed',
+ () async {
+ var controller1 = StreamController<String>();
+ var controller2 = StreamController<String>();
- streamGroup.add(controller1.stream);
- streamGroup.add(controller2.stream);
- await flushMicrotasks();
+ streamGroup.add(controller1.stream);
+ streamGroup.add(controller2.stream);
+ await flushMicrotasks();
- expect(streamGroup.isClosed, isFalse);
- streamGroup.close();
- expect(streamGroup.isClosed, isTrue);
+ expect(streamGroup.isClosed, isFalse);
+ streamGroup.close();
+ expect(streamGroup.isClosed, isTrue);
- streamGroup.remove(controller1.stream);
- await flushMicrotasks();
+ streamGroup.remove(controller1.stream);
+ await flushMicrotasks();
- streamGroup.remove(controller2.stream);
- await flushMicrotasks();
+ streamGroup.remove(controller2.stream);
+ await flushMicrotasks();
- expect(streamGroup.stream.toList(), completion(isEmpty));
- });
+ expect(streamGroup.stream.toList(), completion(isEmpty));
+ },
+ );
});
group('while listening', () {
@@ -685,8 +732,9 @@
});
test('forwards cancel errors', () async {
- var controller =
- StreamController<String>(onCancel: () => throw 'error');
+ var controller = StreamController<String>(
+ onCancel: () => throw 'error',
+ );
streamGroup.add(controller.stream);
streamGroup.stream.listen(null);
@@ -697,8 +745,9 @@
test('forwards cancel futures', () async {
var completer = Completer<void>();
- var controller =
- StreamController<String>(onCancel: () => completer.future);
+ var controller = StreamController<String>(
+ onCancel: () => completer.future,
+ );
streamGroup.stream.listen(null);
await flushMicrotasks();
@@ -725,29 +774,31 @@
expect(streamGroup.remove(controller.stream), isNull);
});
- test('and closed closes the group when the last stream is removed',
- () async {
- var done = false;
- streamGroup.stream.listen(null, onDone: () => done = true);
- await flushMicrotasks();
+ test(
+ 'and closed closes the group when the last stream is removed',
+ () async {
+ var done = false;
+ streamGroup.stream.listen(null, onDone: () => done = true);
+ await flushMicrotasks();
- var controller1 = StreamController<String>();
- var controller2 = StreamController<String>();
+ var controller1 = StreamController<String>();
+ var controller2 = StreamController<String>();
- streamGroup.add(controller1.stream);
- streamGroup.add(controller2.stream);
- await flushMicrotasks();
+ streamGroup.add(controller1.stream);
+ streamGroup.add(controller2.stream);
+ await flushMicrotasks();
- streamGroup.close();
+ streamGroup.close();
- streamGroup.remove(controller1.stream);
- await flushMicrotasks();
- expect(done, isFalse);
+ streamGroup.remove(controller1.stream);
+ await flushMicrotasks();
+ expect(done, isFalse);
- streamGroup.remove(controller2.stream);
- await flushMicrotasks();
- expect(done, isTrue);
- });
+ streamGroup.remove(controller2.stream);
+ await flushMicrotasks();
+ expect(done, isTrue);
+ },
+ );
});
});
@@ -782,56 +833,60 @@
expect(streamGroup.close(), completes);
});
- test('if there are streams, closes the group once those streams close',
- () async {
- var done = false;
- streamGroup.stream.listen(null, onDone: () => done = true);
- await flushMicrotasks();
-
- var controller1 = StreamController<String>();
- var controller2 = StreamController<String>();
-
- streamGroup.add(controller1.stream);
- streamGroup.add(controller2.stream);
- await flushMicrotasks();
-
- streamGroup.close();
- await flushMicrotasks();
- expect(done, isFalse);
-
- controller1.close();
- await flushMicrotasks();
- expect(done, isFalse);
-
- controller2.close();
- await flushMicrotasks();
- expect(done, isTrue);
- });
- });
-
- test('returns a Future that completes once all events are dispatched',
+ test(
+ 'if there are streams, closes the group once those streams close',
() async {
- var events = [];
- streamGroup.stream.listen(events.add);
+ var done = false;
+ streamGroup.stream.listen(null, onDone: () => done = true);
+ await flushMicrotasks();
- var controller = StreamController<String>();
- streamGroup.add(controller.stream);
- await flushMicrotasks();
+ var controller1 = StreamController<String>();
+ var controller2 = StreamController<String>();
- // Add a bunch of events. Each of these will get dispatched in a
- // separate microtask, so we can test that [close] only completes once
- // all of them have dispatched.
- controller.add('one');
- controller.add('two');
- controller.add('three');
- controller.add('four');
- controller.add('five');
- controller.add('six');
- controller.close();
+ streamGroup.add(controller1.stream);
+ streamGroup.add(controller2.stream);
+ await flushMicrotasks();
- await streamGroup.close();
- expect(events, equals(['one', 'two', 'three', 'four', 'five', 'six']));
+ streamGroup.close();
+ await flushMicrotasks();
+ expect(done, isFalse);
+
+ controller1.close();
+ await flushMicrotasks();
+ expect(done, isFalse);
+
+ controller2.close();
+ await flushMicrotasks();
+ expect(done, isTrue);
+ },
+ );
});
+
+ test(
+ 'returns a Future that completes once all events are dispatched',
+ () async {
+ var events = [];
+ streamGroup.stream.listen(events.add);
+
+ var controller = StreamController<String>();
+ streamGroup.add(controller.stream);
+ await flushMicrotasks();
+
+ // Add a bunch of events. Each of these will get dispatched in a
+ // separate microtask, so we can test that [close] only completes once
+ // all of them have dispatched.
+ controller.add('one');
+ controller.add('two');
+ controller.add('three');
+ controller.add('four');
+ controller.add('five');
+ controller.add('six');
+ controller.close();
+
+ await streamGroup.close();
+ expect(events, equals(['one', 'two', 'three', 'four', 'five', 'six']));
+ },
+ );
});
group('onIdle', () {
@@ -906,20 +961,25 @@
var onIdleDone = false;
var streamClosed = false;
- streamGroup.onIdle.listen(expectAsync1((_) {
- expect(streamClosed, isFalse);
- idle = true;
- }), onDone: expectAsync0(() {
- expect(idle, isTrue);
- expect(streamClosed, isTrue);
- onIdleDone = true;
- }));
+ streamGroup.onIdle.listen(
+ expectAsync1((_) {
+ expect(streamClosed, isFalse);
+ idle = true;
+ }),
+ onDone: expectAsync0(() {
+ expect(idle, isTrue);
+ expect(streamClosed, isTrue);
+ onIdleDone = true;
+ }),
+ );
- streamGroup.stream.drain().then(expectAsync1((_) {
- expect(idle, isTrue);
- expect(onIdleDone, isFalse);
- streamClosed = true;
- }));
+ streamGroup.stream.drain().then(
+ expectAsync1((_) {
+ expect(idle, isTrue);
+ expect(onIdleDone, isFalse);
+ streamClosed = true;
+ }),
+ );
var controller = StreamController<String>();
streamGroup.add(controller.stream);
diff --git a/pkgs/async/test/stream_queue_test.dart b/pkgs/async/test/stream_queue_test.dart
index cd4433a..48ebf3c 100644
--- a/pkgs/async/test/stream_queue_test.dart
+++ b/pkgs/async/test/stream_queue_test.dart
@@ -153,8 +153,12 @@
test('multiple requests at the same time', () async {
var events = StreamQueue<int>(createStream());
- var result = await Future.wait(
- [events.next, events.next, events.next, events.next]);
+ var result = await Future.wait([
+ events.next,
+ events.next,
+ events.next,
+ events.next,
+ ]);
expect(result, [1, 2, 3, 4]);
await events.cancel();
});
@@ -261,7 +265,7 @@
skip1.then(sequence(0, 0)),
skip2.then(sequence(0, 1)),
skip3.then(sequence(1, 2)),
- skip4.then(sequence(1, 3))
+ skip4.then(sequence(1, 3)),
]);
await events.cancel();
});
@@ -452,8 +456,13 @@
});
test('multiple requests at the same time', () async {
var events = StreamQueue<int>(createStream());
- var result = await Future.wait(
- [events.peek, events.peek, events.next, events.peek, events.peek]);
+ var result = await Future.wait([
+ events.peek,
+ events.peek,
+ events.next,
+ events.peek,
+ events.peek,
+ ]);
expect(result, [1, 1, 1, 2, 2]);
await events.cancel();
});
@@ -483,13 +492,15 @@
expect(() => events.cancel(), throwsStateError);
});
- test('cancels underlying subscription when called before any event',
- () async {
- var cancelFuture = Future.value(42);
- var controller = StreamController<int>(onCancel: () => cancelFuture);
- var events = StreamQueue<int>(controller.stream);
- expect(await events.cancel(), 42);
- });
+ test(
+ 'cancels underlying subscription when called before any event',
+ () async {
+ var cancelFuture = Future.value(42);
+ var controller = StreamController<int>(onCancel: () => cancelFuture);
+ var events = StreamQueue<int>(controller.stream);
+ expect(await events.cancel(), 42);
+ },
+ );
test('cancels underlying subscription, returns result', () async {
var cancelFuture = Future.value(42);
@@ -523,14 +534,16 @@
expect(controller.hasListener, isFalse);
});
- test('cancels the underlying subscription when called before any event',
- () async {
- var cancelFuture = Future.value(42);
- var controller = StreamController<int>(onCancel: () => cancelFuture);
+ test(
+ 'cancels the underlying subscription when called before any event',
+ () async {
+ var cancelFuture = Future.value(42);
+ var controller = StreamController<int>(onCancel: () => cancelFuture);
- var events = StreamQueue<int>(controller.stream);
- expect(await events.cancel(immediate: true), 42);
- });
+ var events = StreamQueue<int>(controller.stream);
+ expect(await events.cancel(immediate: true), 42);
+ },
+ );
test('closes pending requests', () async {
var events = StreamQueue<int>(createStream());
@@ -541,27 +554,33 @@
await events.cancel(immediate: true);
});
- test('returns the result of closing the underlying subscription',
- () async {
- var controller =
- StreamController<int>(onCancel: () => Future<int>.value(42));
- var events = StreamQueue<int>(controller.stream);
- expect(await events.cancel(immediate: true), 42);
- });
+ test(
+ 'returns the result of closing the underlying subscription',
+ () async {
+ var controller = StreamController<int>(
+ onCancel: () => Future<int>.value(42),
+ );
+ var events = StreamQueue<int>(controller.stream);
+ expect(await events.cancel(immediate: true), 42);
+ },
+ );
- test("listens and then cancels a stream that hasn't been listened to yet",
- () async {
- var wasListened = false;
- var controller =
- StreamController<int>(onListen: () => wasListened = true);
- var events = StreamQueue<int>(controller.stream);
- expect(wasListened, isFalse);
- expect(controller.hasListener, isFalse);
+ test(
+ "listens and then cancels a stream that hasn't been listened to yet",
+ () async {
+ var wasListened = false;
+ var controller = StreamController<int>(
+ onListen: () => wasListened = true,
+ );
+ var events = StreamQueue<int>(controller.stream);
+ expect(wasListened, isFalse);
+ expect(controller.hasListener, isFalse);
- await events.cancel(immediate: true);
- expect(wasListened, isTrue);
- expect(controller.hasListener, isFalse);
- });
+ await events.cancel(immediate: true);
+ expect(wasListened, isTrue);
+ expect(controller.hasListener, isFalse);
+ },
+ );
});
});
@@ -854,22 +873,26 @@
transaction.reject();
});
- test('further child requests act as though the stream was closed',
- () async {
- expect(await queue1.next, 2);
- transaction.reject();
+ test(
+ 'further child requests act as though the stream was closed',
+ () async {
+ expect(await queue1.next, 2);
+ transaction.reject();
- expect(await queue1.hasNext, isFalse);
- expect(queue1.next, throwsStateError);
- });
+ expect(await queue1.hasNext, isFalse);
+ expect(queue1.next, throwsStateError);
+ },
+ );
- test('pending child requests act as though the stream was closed',
- () async {
- expect(await queue1.next, 2);
- expect(queue1.hasNext, completion(isFalse));
- expect(queue1.next, throwsStateError);
- transaction.reject();
- });
+ test(
+ 'pending child requests act as though the stream was closed',
+ () async {
+ expect(await queue1.next, 2);
+ expect(queue1.hasNext, completion(isFalse));
+ expect(queue1.next, throwsStateError);
+ transaction.reject();
+ },
+ );
// Regression test.
test('pending child rest requests emit no more events', () async {
@@ -879,8 +902,10 @@
var queue = transaction.newQueue();
// This should emit no more events after the transaction is rejected.
- queue.rest.listen(expectAsync1((_) {}, count: 3),
- onDone: expectAsync0(() {}, count: 0));
+ queue.rest.listen(
+ expectAsync1((_) {}, count: 3),
+ onDone: expectAsync0(() {}, count: 0),
+ );
controller.add(1);
controller.add(2);
@@ -959,22 +984,26 @@
transaction.commit(queue1);
});
- test('further child requests act as though the stream was closed',
- () async {
- expect(await queue2.next, 2);
- transaction.commit(queue2);
+ test(
+ 'further child requests act as though the stream was closed',
+ () async {
+ expect(await queue2.next, 2);
+ transaction.commit(queue2);
- expect(await queue1.hasNext, isFalse);
- expect(queue1.next, throwsStateError);
- });
+ expect(await queue1.hasNext, isFalse);
+ expect(queue1.next, throwsStateError);
+ },
+ );
- test('pending child requests act as though the stream was closed',
- () async {
- expect(await queue2.next, 2);
- expect(queue1.hasNext, completion(isFalse));
- expect(queue1.next, throwsStateError);
- transaction.commit(queue2);
- });
+ test(
+ 'pending child requests act as though the stream was closed',
+ () async {
+ expect(await queue2.next, 2);
+ expect(queue1.hasNext, completion(isFalse));
+ expect(queue1.next, throwsStateError);
+ transaction.commit(queue2);
+ },
+ );
test('further requests act as though the stream was closed', () async {
expect(await queue1.next, 2);
@@ -1031,22 +1060,26 @@
});
test('passes a copy of the parent queue', () async {
- await events.withTransaction(expectAsync1((queue) async {
- expect(await queue.next, 2);
- expect(await queue.next, 3);
- expect(await queue.next, 4);
- expect(await queue.hasNext, isFalse);
- return true;
- }));
+ await events.withTransaction(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ expect(await queue.next, 3);
+ expect(await queue.next, 4);
+ expect(await queue.hasNext, isFalse);
+ return true;
+ }),
+ );
});
test(
'the parent queue continues from the child position if it returns '
'true', () async {
- await events.withTransaction(expectAsync1((queue) async {
- expect(await queue.next, 2);
- return true;
- }));
+ await events.withTransaction(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ return true;
+ }),
+ );
expect(await events.next, 3);
});
@@ -1054,19 +1087,26 @@
test(
'the parent queue continues from its original position if it returns '
'false', () async {
- await events.withTransaction(expectAsync1((queue) async {
- expect(await queue.next, 2);
- return false;
- }));
+ await events.withTransaction(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ return false;
+ }),
+ );
expect(await events.next, 2);
});
test('the parent queue continues from the child position if it throws', () {
- expect(events.withTransaction(expectAsync1((queue) async {
- expect(await queue.next, 2);
- throw 'oh no';
- })), throwsA('oh no'));
+ expect(
+ events.withTransaction(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ throw 'oh no';
+ }),
+ ),
+ throwsA('oh no'),
+ );
expect(events.next, completion(3));
});
@@ -1085,53 +1125,69 @@
});
test('passes a copy of the parent queue', () async {
- await events.cancelable(expectAsync1((queue) async {
- expect(await queue.next, 2);
- expect(await queue.next, 3);
- expect(await queue.next, 4);
- expect(await queue.hasNext, isFalse);
- })).value;
+ await events.cancelable(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ expect(await queue.next, 3);
+ expect(await queue.next, 4);
+ expect(await queue.hasNext, isFalse);
+ }),
+ ).value;
});
- test('the parent queue continues from the child position by default',
- () async {
- await events.cancelable(expectAsync1((queue) async {
- expect(await queue.next, 2);
- })).value;
+ test(
+ 'the parent queue continues from the child position by default',
+ () async {
+ await events.cancelable(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ }),
+ ).value;
- expect(await events.next, 3);
- });
+ expect(await events.next, 3);
+ },
+ );
test(
'the parent queue continues from the child position if an error is '
'thrown', () async {
expect(
- events.cancelable(expectAsync1((queue) async {
+ events.cancelable(
+ expectAsync1((queue) async {
expect(await queue.next, 2);
throw 'oh no';
- })).value,
- throwsA('oh no'));
+ }),
+ ).value,
+ throwsA('oh no'),
+ );
expect(events.next, completion(3));
});
- test('the parent queue continues from the original position if canceled',
- () async {
- var operation = events.cancelable(expectAsync1((queue) async {
- expect(await queue.next, 2);
- }));
- operation.cancel();
+ test(
+ 'the parent queue continues from the original position if canceled',
+ () async {
+ var operation = events.cancelable(
+ expectAsync1((queue) async {
+ expect(await queue.next, 2);
+ }),
+ );
+ operation.cancel();
- expect(await events.next, 2);
- });
+ expect(await events.next, 2);
+ },
+ );
test('forwards the value from the callback', () async {
expect(
- await events.cancelable(expectAsync1((queue) async {
+ await events.cancelable(
+ expectAsync1((queue) async {
expect(await queue.next, 2);
return 'value';
- })).value,
- 'value');
+ }),
+ ).value,
+ 'value',
+ );
});
});
@@ -1158,8 +1214,10 @@
// Test expecting [startIndex .. startIndex + 9] as events using
// `take(10)`.
void takeTest(int startIndex) {
- expect(events.take(10),
- completion(List.generate(10, (i) => startIndex + i)));
+ expect(
+ events.take(10),
+ completion(List.generate(10, (i) => startIndex + i)),
+ );
}
var tests = [nextTest, skipTest, takeTest];
@@ -1174,8 +1232,10 @@
}
}
// Then expect 20 more events as a `rest` call.
- expect(events.rest.toList(),
- completion(List.generate(20, (i) => counter + i)));
+ expect(
+ events.rest.toList(),
+ completion(List.generate(20, (i) => counter + i)),
+ );
});
}
diff --git a/pkgs/async/test/stream_sink_completer_test.dart b/pkgs/async/test/stream_sink_completer_test.dart
index 3a6f25b..aa8447f 100644
--- a/pkgs/async/test/stream_sink_completer_test.dart
+++ b/pkgs/async/test/stream_sink_completer_test.dart
@@ -79,9 +79,11 @@
completer.setDestinationSink(sink);
var closeCompleted = false;
- completer.sink.close().then(expectAsync1((_) {
- closeCompleted = true;
- }));
+ completer.sink.close().then(
+ expectAsync1((_) {
+ closeCompleted = true;
+ }),
+ );
await flushMicrotasks();
expect(closeCompleted, isFalse);
@@ -186,9 +188,11 @@
test('the future from the inner close() is returned', () async {
var closeCompleted = false;
- completer.sink.close().then(expectAsync1((_) {
- closeCompleted = true;
- }));
+ completer.sink.close().then(
+ expectAsync1((_) {
+ closeCompleted = true;
+ }),
+ );
await flushMicrotasks();
var closeCompleter = Completer<void>();
@@ -235,27 +239,31 @@
});
});
- test('the sink is closed, the destination is set, then done is read',
- () async {
- expect(completer.sink.close(), completes);
- await flushMicrotasks();
+ test(
+ 'the sink is closed, the destination is set, then done is read',
+ () async {
+ expect(completer.sink.close(), completes);
+ await flushMicrotasks();
- completer.setDestinationSink(TestSink());
- await flushMicrotasks();
+ completer.setDestinationSink(TestSink());
+ await flushMicrotasks();
- expect(completer.sink.done, completes);
- });
+ expect(completer.sink.done, completes);
+ },
+ );
- test('done is read, the destination is set, then the sink is closed',
- () async {
- expect(completer.sink.done, completes);
- await flushMicrotasks();
+ test(
+ 'done is read, the destination is set, then the sink is closed',
+ () async {
+ expect(completer.sink.done, completes);
+ await flushMicrotasks();
- completer.setDestinationSink(TestSink());
- await flushMicrotasks();
+ completer.setDestinationSink(TestSink());
+ await flushMicrotasks();
- expect(completer.sink.close(), completes);
- });
+ expect(completer.sink.close(), completes);
+ },
+ );
group('fromFuture()', () {
test('with a successful completion', () async {
diff --git a/pkgs/async/test/stream_sink_transformer_test.dart b/pkgs/async/test/stream_sink_transformer_test.dart
index caea349..9b43718 100644
--- a/pkgs/async/test/stream_sink_transformer_test.dart
+++ b/pkgs/async/test/stream_sink_transformer_test.dart
@@ -18,15 +18,21 @@
group('fromStreamTransformer', () {
test('transforms data events', () {
var transformer = StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer.fromHandlers(handleData: (int i, sink) {
- sink.add(i * 2);
- }));
+ StreamTransformer.fromHandlers(
+ handleData: (int i, sink) {
+ sink.add(i * 2);
+ },
+ ),
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(results.add, onDone: expectAsync0(() {
- expect(results, equals([2, 4, 6]));
- }));
+ controller.stream.listen(
+ results.add,
+ onDone: expectAsync0(() {
+ expect(results, equals([2, 4, 6]));
+ }),
+ );
sink.add(1);
sink.add(2);
@@ -36,18 +42,24 @@
test('transforms error events', () {
var transformer = StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer.fromHandlers(handleError: (i, stackTrace, sink) {
- sink.addError((i as num) * 2, stackTrace);
- }));
+ StreamTransformer.fromHandlers(
+ handleError: (i, stackTrace, sink) {
+ sink.addError((i as num) * 2, stackTrace);
+ },
+ ),
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(expectAsync1((_) {}, count: 0),
- onError: (Object error, stackTrace) {
- results.add(error);
- }, onDone: expectAsync0(() {
- expect(results, equals([2, 4, 6]));
- }));
+ controller.stream.listen(
+ expectAsync1((_) {}, count: 0),
+ onError: (Object error, stackTrace) {
+ results.add(error);
+ },
+ onDone: expectAsync0(() {
+ expect(results, equals([2, 4, 6]));
+ }),
+ );
sink.addError(1);
sink.addError(2);
@@ -57,23 +69,30 @@
test('transforms done events', () {
var transformer = StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer.fromHandlers(handleDone: (sink) {
- sink.add(1);
- sink.close();
- }));
+ StreamTransformer.fromHandlers(
+ handleDone: (sink) {
+ sink.add(1);
+ sink.close();
+ },
+ ),
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(results.add, onDone: expectAsync0(() {
- expect(results, equals([1]));
- }));
+ controller.stream.listen(
+ results.add,
+ onDone: expectAsync0(() {
+ expect(results, equals([1]));
+ }),
+ );
sink.close();
});
test('forwards the future from inner.close', () async {
var transformer = StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer.fromHandlers());
+ StreamTransformer.fromHandlers(),
+ );
var innerSink = CompleterStreamSink();
var sink = transformer.bind(innerSink);
@@ -96,9 +115,12 @@
test("doesn't top-level the future from inner.close", () async {
var transformer = StreamSinkTransformer.fromStreamTransformer(
- StreamTransformer.fromHandlers(handleData: (_, sink) {
- sink.close();
- }));
+ StreamTransformer.fromHandlers(
+ handleData: (_, sink) {
+ sink.close();
+ },
+ ),
+ );
var innerSink = CompleterStreamSink();
var sink = transformer.bind(innerSink);
@@ -116,16 +138,20 @@
group('fromHandlers', () {
test('transforms data events', () {
- var transformer =
- StreamSinkTransformer.fromHandlers(handleData: (int i, sink) {
- sink.add(i * 2);
- });
+ var transformer = StreamSinkTransformer.fromHandlers(
+ handleData: (int i, sink) {
+ sink.add(i * 2);
+ },
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(results.add, onDone: expectAsync0(() {
- expect(results, equals([2, 4, 6]));
- }));
+ controller.stream.listen(
+ results.add,
+ onDone: expectAsync0(() {
+ expect(results, equals([2, 4, 6]));
+ }),
+ );
sink.add(1);
sink.add(2);
@@ -135,18 +161,22 @@
test('transforms error events', () {
var transformer = StreamSinkTransformer.fromHandlers(
- handleError: (i, stackTrace, sink) {
- sink.addError((i as num) * 2, stackTrace);
- });
+ handleError: (i, stackTrace, sink) {
+ sink.addError((i as num) * 2, stackTrace);
+ },
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(expectAsync1((_) {}, count: 0),
- onError: (Object error, stackTrace) {
- results.add(error);
- }, onDone: expectAsync0(() {
- expect(results, equals([2, 4, 6]));
- }));
+ controller.stream.listen(
+ expectAsync1((_) {}, count: 0),
+ onError: (Object error, stackTrace) {
+ results.add(error);
+ },
+ onDone: expectAsync0(() {
+ expect(results, equals([2, 4, 6]));
+ }),
+ );
sink.addError(1);
sink.addError(2);
@@ -155,16 +185,21 @@
});
test('transforms done events', () {
- var transformer = StreamSinkTransformer.fromHandlers(handleDone: (sink) {
- sink.add(1);
- sink.close();
- });
+ var transformer = StreamSinkTransformer.fromHandlers(
+ handleDone: (sink) {
+ sink.add(1);
+ sink.close();
+ },
+ );
var sink = transformer.bind(controller.sink);
var results = [];
- controller.stream.listen(results.add, onDone: expectAsync0(() {
- expect(results, equals([1]));
- }));
+ controller.stream.listen(
+ results.add,
+ onDone: expectAsync0(() {
+ expect(results, equals([1]));
+ }),
+ );
sink.close();
});
@@ -192,10 +227,11 @@
});
test("doesn't top-level the future from inner.close", () async {
- var transformer =
- StreamSinkTransformer.fromHandlers(handleData: (_, sink) {
- sink.close();
- });
+ var transformer = StreamSinkTransformer.fromHandlers(
+ handleData: (_, sink) {
+ sink.close();
+ },
+ );
var innerSink = CompleterStreamSink();
var sink = transformer.bind(innerSink);
diff --git a/pkgs/async/test/stream_splitter_test.dart b/pkgs/async/test/stream_splitter_test.dart
index 27921db..ff916b2 100644
--- a/pkgs/async/test/stream_splitter_test.dart
+++ b/pkgs/async/test/stream_splitter_test.dart
@@ -17,27 +17,29 @@
splitter = StreamSplitter<int>(controller.stream);
});
- test("a branch that's created before the stream starts to replay it",
- () async {
- var events = [];
- var branch = splitter.split();
- splitter.close();
- branch.listen(events.add);
+ test(
+ "a branch that's created before the stream starts to replay it",
+ () async {
+ var events = [];
+ var branch = splitter.split();
+ splitter.close();
+ branch.listen(events.add);
- controller.add(1);
- await flushMicrotasks();
- expect(events, equals([1]));
+ controller.add(1);
+ await flushMicrotasks();
+ expect(events, equals([1]));
- controller.add(2);
- await flushMicrotasks();
- expect(events, equals([1, 2]));
+ controller.add(2);
+ await flushMicrotasks();
+ expect(events, equals([1, 2]));
- controller.add(3);
- await flushMicrotasks();
- expect(events, equals([1, 2, 3]));
+ controller.add(3);
+ await flushMicrotasks();
+ expect(events, equals([1, 2, 3]));
- controller.close();
- });
+ controller.close();
+ },
+ );
test('a branch replays error events as well as data events', () {
var branch = splitter.split();
@@ -50,46 +52,53 @@
var count = 0;
branch.listen(
- expectAsync1((value) {
- expect(count, anyOf(0, 2));
- expect(value, equals(count + 1));
- count++;
- }, count: 2), onError: expectAsync1((error) {
- expect(count, equals(1));
- expect(error, equals('error'));
- count++;
- }), onDone: expectAsync0(() {
- expect(count, equals(3));
- }));
+ expectAsync1((value) {
+ expect(count, anyOf(0, 2));
+ expect(value, equals(count + 1));
+ count++;
+ }, count: 2),
+ onError: expectAsync1((error) {
+ expect(count, equals(1));
+ expect(error, equals('error'));
+ count++;
+ }),
+ onDone: expectAsync0(() {
+ expect(count, equals(3));
+ }),
+ );
});
- test("a branch that's created in the middle of a stream replays it",
- () async {
- controller.add(1);
- controller.add(2);
- await flushMicrotasks();
+ test(
+ "a branch that's created in the middle of a stream replays it",
+ () async {
+ controller.add(1);
+ controller.add(2);
+ await flushMicrotasks();
- var branch = splitter.split();
- splitter.close();
+ var branch = splitter.split();
+ splitter.close();
- controller.add(3);
- controller.add(4);
- controller.close();
+ controller.add(3);
+ controller.add(4);
+ controller.close();
- expect(branch.toList(), completion(equals([1, 2, 3, 4])));
- });
+ expect(branch.toList(), completion(equals([1, 2, 3, 4])));
+ },
+ );
- test("a branch that's created after the stream is finished replays it",
- () async {
- controller.add(1);
- controller.add(2);
- controller.add(3);
- controller.close();
- await flushMicrotasks();
+ test(
+ "a branch that's created after the stream is finished replays it",
+ () async {
+ controller.add(1);
+ controller.add(2);
+ controller.add(3);
+ controller.close();
+ await flushMicrotasks();
- expect(splitter.split().toList(), completion(equals([1, 2, 3])));
- splitter.close();
- });
+ expect(splitter.split().toList(), completion(equals([1, 2, 3])));
+ splitter.close();
+ },
+ );
test('creates single-subscription branches', () async {
var branch = splitter.split();
diff --git a/pkgs/async/test/stream_zip_test.dart b/pkgs/async/test/stream_zip_test.dart
index 147d419..69066ba 100644
--- a/pkgs/async/test/stream_zip_test.dart
+++ b/pkgs/async/test/stream_zip_test.dart
@@ -39,76 +39,94 @@
void testZip(Iterable<Stream> streams, Iterable expectedData) {
var data = [];
Stream zip = StreamZip(streams);
- zip.listen(data.add, onDone: expectAsync0(() {
- expect(data, equals(expectedData));
- }));
+ zip.listen(
+ data.add,
+ onDone: expectAsync0(() {
+ expect(data, equals(expectedData));
+ }),
+ );
}
test('Basic', () {
- testZip([
- mks([1, 2, 3]),
- mks([4, 5, 6]),
- mks([7, 8, 9])
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3]),
+ mks([4, 5, 6]),
+ mks([7, 8, 9]),
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Uneven length 1', () {
- testZip([
- mks([1, 2, 3, 99, 100]),
- mks([4, 5, 6]),
- mks([7, 8, 9])
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3, 99, 100]),
+ mks([4, 5, 6]),
+ mks([7, 8, 9]),
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Uneven length 2', () {
- testZip([
- mks([1, 2, 3]),
- mks([4, 5, 6, 99, 100]),
- mks([7, 8, 9])
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3]),
+ mks([4, 5, 6, 99, 100]),
+ mks([7, 8, 9]),
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Uneven length 3', () {
- testZip([
- mks([1, 2, 3]),
- mks([4, 5, 6]),
- mks([7, 8, 9, 99, 100])
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3]),
+ mks([4, 5, 6]),
+ mks([7, 8, 9, 99, 100]),
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Uneven length 4', () {
- testZip([
- mks([1, 2, 3, 98]),
- mks([4, 5, 6]),
- mks([7, 8, 9, 99, 100])
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3, 98]),
+ mks([4, 5, 6]),
+ mks([7, 8, 9, 99, 100]),
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Empty 1', () {
testZip([
mks([]),
mks([4, 5, 6]),
- mks([7, 8, 9])
+ mks([7, 8, 9]),
], []);
});
@@ -116,7 +134,7 @@
testZip([
mks([1, 2, 3]),
mks([]),
- mks([7, 8, 9])
+ mks([7, 8, 9]),
], []);
});
@@ -124,7 +142,7 @@
testZip([
mks([1, 2, 3]),
mks([4, 5, 6]),
- mks([])
+ mks([]),
], []);
});
@@ -133,30 +151,34 @@
});
test('Single Source', () {
- testZip([
- mks([1, 2, 3])
- ], [
- [1],
- [2],
- [3]
- ]);
+ testZip(
+ [
+ mks([1, 2, 3]),
+ ],
+ [
+ [1],
+ [2],
+ [3],
+ ],
+ );
});
test('Other-streams', () {
var st1 = mks([1, 2, 3, 4, 5, 6]).where((x) => x < 4);
- Stream st2 =
- Stream.periodic(const Duration(milliseconds: 5), (x) => x + 4).take(3);
+ Stream st2 = Stream.periodic(
+ const Duration(milliseconds: 5),
+ (x) => x + 4,
+ ).take(3);
var c = StreamController.broadcast();
var st3 = c.stream;
- testZip([
- st1,
- st2,
- st3
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ testZip(
+ [st1, st2, st3],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
c
..add(7)
..add(8)
@@ -166,62 +188,67 @@
test('Error 1', () {
expect(
- StreamZip([
- streamError(mks([1, 2, 3]), 2, 'BAD-1'),
- mks([4, 5, 6]),
- mks([7, 8, 9])
- ]).toList(),
- throwsA(equals('BAD-1')));
+ StreamZip([
+ streamError(mks([1, 2, 3]), 2, 'BAD-1'),
+ mks([4, 5, 6]),
+ mks([7, 8, 9]),
+ ]).toList(),
+ throwsA(equals('BAD-1')),
+ );
});
test('Error 2', () {
expect(
- StreamZip([
- mks([1, 2, 3]),
- streamError(mks([4, 5, 6]), 5, 'BAD-2'),
- mks([7, 8, 9])
- ]).toList(),
- throwsA(equals('BAD-2')));
+ StreamZip([
+ mks([1, 2, 3]),
+ streamError(mks([4, 5, 6]), 5, 'BAD-2'),
+ mks([7, 8, 9]),
+ ]).toList(),
+ throwsA(equals('BAD-2')),
+ );
});
test('Error 3', () {
expect(
- StreamZip([
- mks([1, 2, 3]),
- mks([4, 5, 6]),
- streamError(mks([7, 8, 9]), 8, 'BAD-3')
- ]).toList(),
- throwsA(equals('BAD-3')));
+ StreamZip([
+ mks([1, 2, 3]),
+ mks([4, 5, 6]),
+ streamError(mks([7, 8, 9]), 8, 'BAD-3'),
+ ]).toList(),
+ throwsA(equals('BAD-3')),
+ );
});
test('Error at end', () {
expect(
- StreamZip([
- mks([1, 2, 3]),
- streamError(mks([4, 5, 6]), 6, 'BAD-4'),
- mks([7, 8, 9])
- ]).toList(),
- throwsA(equals('BAD-4')));
+ StreamZip([
+ mks([1, 2, 3]),
+ streamError(mks([4, 5, 6]), 6, 'BAD-4'),
+ mks([7, 8, 9]),
+ ]).toList(),
+ throwsA(equals('BAD-4')),
+ );
});
test('Error before first end', () {
// StreamControllers' streams with no "close" called will never be done,
// so the fourth event of the first stream is guaranteed to come first.
expect(
- StreamZip([
- streamError(mks([1, 2, 3, 4]), 4, 'BAD-5'),
- (StreamController()
- ..add(4)
- ..add(5)
- ..add(6))
- .stream,
- (StreamController()
- ..add(7)
- ..add(8)
- ..add(9))
- .stream
- ]).toList(),
- throwsA(equals('BAD-5')));
+ StreamZip([
+ streamError(mks([1, 2, 3, 4]), 4, 'BAD-5'),
+ (StreamController()
+ ..add(4)
+ ..add(5)
+ ..add(6))
+ .stream,
+ (StreamController()
+ ..add(7)
+ ..add(8)
+ ..add(9))
+ .stream,
+ ]).toList(),
+ throwsA(equals('BAD-5')),
+ );
});
test('Error after first end', () {
@@ -232,38 +259,48 @@
..add(9);
// Transformer that puts error into controller when one of the first two
// streams have sent a done event.
- var trans =
- StreamTransformer<int, int>.fromHandlers(handleDone: (EventSink s) {
- Timer.run(() {
- controller.addError('BAD-6');
- });
- s.close();
- });
- testZip([
- mks([1, 2, 3]).transform(trans),
- mks([4, 5, 6]).transform(trans),
- controller.stream
- ], [
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]);
+ var trans = StreamTransformer<int, int>.fromHandlers(
+ handleDone: (EventSink s) {
+ Timer.run(() {
+ controller.addError('BAD-6');
+ });
+ s.close();
+ },
+ );
+ testZip(
+ [
+ mks([1, 2, 3]).transform(trans),
+ mks([4, 5, 6]).transform(trans),
+ controller.stream,
+ ],
+ [
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ],
+ );
});
test('Pause/Resume', () {
var sc1p = 0;
- var c1 = StreamController(onPause: () {
- sc1p++;
- }, onResume: () {
- sc1p--;
- });
+ var c1 = StreamController(
+ onPause: () {
+ sc1p++;
+ },
+ onResume: () {
+ sc1p--;
+ },
+ );
var sc2p = 0;
- var c2 = StreamController(onPause: () {
- sc2p++;
- }, onResume: () {
- sc2p--;
- });
+ var c2 = StreamController(
+ onPause: () {
+ sc2p++;
+ },
+ onResume: () {
+ sc2p--;
+ },
+ );
var done = expectAsync0(() {
expect(sc1p, equals(1));
@@ -320,17 +357,19 @@
var sz = StreamZip([s1, s2]);
var ctr = 0;
late StreamSubscription sub;
- sub = sz.listen(expectAsync1((v) {
- expect(v, equals([ctr * 2, ctr * 2 + 1]));
- if (ctr == 1) {
- sub.pause(Future<void>.delayed(const Duration(milliseconds: 25)));
- } else if (ctr == 2) {
- sub.pause();
- Future<void>.delayed(const Duration(milliseconds: 25)).then((_) {
- sub.resume();
- });
- }
- ctr++;
- }, count: 4));
+ sub = sz.listen(
+ expectAsync1((v) {
+ expect(v, equals([ctr * 2, ctr * 2 + 1]));
+ if (ctr == 1) {
+ sub.pause(Future<void>.delayed(const Duration(milliseconds: 25)));
+ } else if (ctr == 2) {
+ sub.pause();
+ Future<void>.delayed(const Duration(milliseconds: 25)).then((_) {
+ sub.resume();
+ });
+ }
+ ctr++;
+ }, count: 4),
+ );
});
}
diff --git a/pkgs/async/test/stream_zip_zone_test.dart b/pkgs/async/test/stream_zip_zone_test.dart
index a18c776..f36f7ed 100644
--- a/pkgs/async/test/stream_zip_zone_test.dart
+++ b/pkgs/async/test/stream_zip_zone_test.dart
@@ -17,7 +17,10 @@
testStream('broadcast-async', controller, controller.stream);
controller = StreamController<void>();
testStream(
- 'asbroadcast-async', controller, controller.stream.asBroadcastStream());
+ 'asbroadcast-async',
+ controller,
+ controller.stream.asBroadcastStream(),
+ );
controller = StreamController(sync: true);
testStream('singlesub-sync', controller, controller.stream);
@@ -25,7 +28,10 @@
testStream('broadcast-sync', controller, controller.stream);
controller = StreamController(sync: true);
testStream(
- 'asbroadcast-sync', controller, controller.stream.asBroadcastStream());
+ 'asbroadcast-sync',
+ controller,
+ controller.stream.asBroadcastStream(),
+ );
}
void testStream(String name, StreamController controller, Stream stream) {
@@ -34,32 +40,38 @@
runZoned(() {
var newZone1 = Zone.current;
late StreamSubscription sub;
- sub = stream.listen(expectAsync1((v) {
- expect(v, 42);
- expect(Zone.current, newZone1);
- outer.run(() {
- sub.onData(expectAsync1((v) {
- expect(v, 37);
- expect(Zone.current, newZone1);
- runZoned(() {
- sub.onData(expectAsync1((v) {
- expect(v, 87);
+ sub = stream.listen(
+ expectAsync1((v) {
+ expect(v, 42);
+ expect(Zone.current, newZone1);
+ outer.run(() {
+ sub.onData(
+ expectAsync1((v) {
+ expect(v, 37);
expect(Zone.current, newZone1);
- }));
- });
- if (controller is SynchronousStreamController) {
- scheduleMicrotask(() => controller.add(87));
- } else {
- controller.add(87);
- }
- }));
- });
- if (controller is SynchronousStreamController) {
- scheduleMicrotask(() => controller.add(37));
- } else {
- controller.add(37);
- }
- }));
+ runZoned(() {
+ sub.onData(
+ expectAsync1((v) {
+ expect(v, 87);
+ expect(Zone.current, newZone1);
+ }),
+ );
+ });
+ if (controller is SynchronousStreamController) {
+ scheduleMicrotask(() => controller.add(87));
+ } else {
+ controller.add(87);
+ }
+ }),
+ );
+ });
+ if (controller is SynchronousStreamController) {
+ scheduleMicrotask(() => controller.add(37));
+ } else {
+ controller.add(37);
+ }
+ }),
+ );
});
controller.add(42);
});
diff --git a/pkgs/async/test/subscription_stream_test.dart b/pkgs/async/test/subscription_stream_test.dart
index acdbdf1..9081b60 100644
--- a/pkgs/async/test/subscription_stream_test.dart
+++ b/pkgs/async/test/subscription_stream_test.dart
@@ -79,16 +79,22 @@
var cancelCompleter = Completer<void>();
var source = createErrorStream(cancelCompleter);
onCancel = cancelCompleter.future;
- var sourceSubscription =
- source.listen(null, cancelOnError: sourceCancels);
+ var sourceSubscription = source.listen(
+ null,
+ cancelOnError: sourceCancels,
+ );
subscriptionStream = SubscriptionStream<int>(sourceSubscription);
});
test('- subscriptionStream: no', () async {
var done = Completer<void>();
var events = [];
- subscriptionStream.listen(events.add,
- onError: events.add, onDone: done.complete, cancelOnError: false);
+ subscriptionStream.listen(
+ events.add,
+ onError: events.add,
+ onDone: done.complete,
+ cancelOnError: false,
+ );
var expected = [1, 2, 'To err is divine!'];
if (sourceCancels) {
await onCancel;
@@ -109,13 +115,15 @@
test('- subscriptionStream: yes', () async {
var completer = Completer<void>();
var events = <Object?>[];
- subscriptionStream.listen(events.add,
- onError: (Object? value) {
- events.add(value);
- completer.complete();
- },
- onDone: () => throw 'should not happen',
- cancelOnError: true);
+ subscriptionStream.listen(
+ events.add,
+ onError: (Object? value) {
+ events.add(value);
+ completer.complete();
+ },
+ onDone: () => throw 'should not happen',
+ cancelOnError: true,
+ );
await completer.future;
await flushMicrotasks();
expect(events, [1, 2, 'To err is divine!']);
@@ -127,22 +135,30 @@
group(cancelOnError ? 'yes' : 'no', () {
test('- no error, value goes to asFuture', () async {
var stream = createStream();
- var sourceSubscription =
- stream.listen(null, cancelOnError: cancelOnError);
+ var sourceSubscription = stream.listen(
+ null,
+ cancelOnError: cancelOnError,
+ );
var subscriptionStream = SubscriptionStream(sourceSubscription);
- var subscription =
- subscriptionStream.listen(null, cancelOnError: cancelOnError);
+ var subscription = subscriptionStream.listen(
+ null,
+ cancelOnError: cancelOnError,
+ );
expect(subscription.asFuture(42), completion(42));
});
test('- error goes to asFuture', () async {
var stream = createErrorStream();
- var sourceSubscription =
- stream.listen(null, cancelOnError: cancelOnError);
+ var sourceSubscription = stream.listen(
+ null,
+ cancelOnError: cancelOnError,
+ );
var subscriptionStream = SubscriptionStream(sourceSubscription);
- var subscription =
- subscriptionStream.listen(null, cancelOnError: cancelOnError);
+ var subscription = subscriptionStream.listen(
+ null,
+ cancelOnError: cancelOnError,
+ );
expect(subscription.asFuture(), throwsA(anything));
});
});
@@ -160,10 +176,12 @@
completer.complete();
}
- subscriptionStream.listen((_) {},
- onError: f,
- onDone: () => throw 'should not happen',
- cancelOnError: true);
+ subscriptionStream.listen(
+ (_) {},
+ onError: f,
+ onDone: () => throw 'should not happen',
+ cancelOnError: true,
+ );
await completer.future;
await flushMicrotasks();
});
@@ -174,12 +192,14 @@
var sourceSubscription = stream.listen(null, cancelOnError: true);
var subscriptionStream = SubscriptionStream(sourceSubscription);
- subscriptionStream.listen((_) {},
- onError: (error, stackTrace) {
- completer.complete();
- },
- onDone: () => throw 'should not happen',
- cancelOnError: true);
+ subscriptionStream.listen(
+ (_) {},
+ onError: (error, stackTrace) {
+ completer.complete();
+ },
+ onDone: () => throw 'should not happen',
+ cancelOnError: true,
+ );
await completer.future;
await flushMicrotasks();
});
@@ -194,10 +214,12 @@
completer.complete();
}
- subscriptionStream.listen((_) {},
- onError: f,
- onDone: () => throw 'should not happen',
- cancelOnError: true);
+ subscriptionStream.listen(
+ (_) {},
+ onError: f,
+ onDone: () => throw 'should not happen',
+ cancelOnError: true,
+ );
await completer.future;
await flushMicrotasks();
});
@@ -208,12 +230,14 @@
var sourceSubscription = stream.listen(null, cancelOnError: true);
var subscriptionStream = SubscriptionStream(sourceSubscription);
- subscriptionStream.listen((_) {},
- onError: (error) {
- completer.complete();
- },
- onDone: () => throw 'should not happen',
- cancelOnError: true);
+ subscriptionStream.listen(
+ (_) {},
+ onError: (error) {
+ completer.complete();
+ },
+ onDone: () => throw 'should not happen',
+ cancelOnError: true,
+ );
await completer.future;
await flushMicrotasks();
});
diff --git a/pkgs/async/test/subscription_transformer_test.dart b/pkgs/async/test/subscription_transformer_test.dart
index 53610e1..1ca6a42 100644
--- a/pkgs/async/test/subscription_transformer_test.dart
+++ b/pkgs/async/test/subscription_transformer_test.dart
@@ -14,19 +14,22 @@
test('forwards cancellation', () async {
var isCanceled = false;
var cancelCompleter = Completer<void>();
- var controller =
- StreamController(onCancel: expectAsync0<Future<void>>(() {
- isCanceled = true;
- return cancelCompleter.future;
- }));
+ var controller = StreamController(
+ onCancel: expectAsync0<Future<void>>(() {
+ isCanceled = true;
+ return cancelCompleter.future;
+ }),
+ );
var subscription = controller.stream
.transform(subscriptionTransformer())
.listen(expectAsync1((_) {}, count: 0));
var cancelFired = false;
- subscription.cancel().then(expectAsync1((_) {
- cancelFired = true;
- }));
+ subscription.cancel().then(
+ expectAsync1((_) {
+ cancelFired = true;
+ }),
+ );
await flushMicrotasks();
expect(isCanceled, isTrue);
@@ -84,15 +87,20 @@
test('invokes the callback when the subscription is canceled', () async {
var isCanceled = false;
var callbackInvoked = false;
- var controller = StreamController(onCancel: expectAsync0(() {
- isCanceled = true;
- }));
+ var controller = StreamController(
+ onCancel: expectAsync0(() {
+ isCanceled = true;
+ }),
+ );
var subscription = controller.stream.transform(
- subscriptionTransformer(handleCancel: expectAsync1((inner) {
- callbackInvoked = true;
- inner.cancel();
- return Future.value();
- }))).listen(expectAsync1((_) {}, count: 0));
+ subscriptionTransformer(
+ handleCancel: expectAsync1((inner) {
+ callbackInvoked = true;
+ inner.cancel();
+ return Future.value();
+ }),
+ ),
+ ).listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
expect(callbackInvoked, isFalse);
@@ -108,19 +116,26 @@
var completer = Completer<void>();
var controller = StreamController<void>();
var subscription = controller.stream
- .transform(subscriptionTransformer(
- handleCancel: expectAsync1((inner) => completer.future)))
+ .transform(
+ subscriptionTransformer(
+ handleCancel: expectAsync1((inner) => completer.future),
+ ),
+ )
.listen(expectAsync1((_) {}, count: 0));
var cancelFired1 = false;
- subscription.cancel().then(expectAsync1((_) {
- cancelFired1 = true;
- }));
+ subscription.cancel().then(
+ expectAsync1((_) {
+ cancelFired1 = true;
+ }),
+ );
var cancelFired2 = false;
- subscription.cancel().then(expectAsync1((_) {
- cancelFired2 = true;
- }));
+ subscription.cancel().then(
+ expectAsync1((_) {
+ cancelFired2 = true;
+ }),
+ );
await flushMicrotasks();
expect(cancelFired1, isFalse);
@@ -138,11 +153,14 @@
var pauseCount = 0;
var controller = StreamController<void>();
var subscription = controller.stream
- .transform(subscriptionTransformer(
+ .transform(
+ subscriptionTransformer(
handlePause: expectAsync1((inner) {
- pauseCount++;
- inner.pause();
- }, count: 3)))
+ pauseCount++;
+ inner.pause();
+ }, count: 3),
+ ),
+ )
.listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
@@ -166,19 +184,24 @@
expect(pauseCount, equals(3));
});
- test("doesn't invoke the callback when the subscription has been canceled",
- () async {
- var controller = StreamController<void>();
- var subscription = controller.stream
- .transform(subscriptionTransformer(
- handlePause: expectAsync1((_) {}, count: 0)))
- .listen(expectAsync1((_) {}, count: 0));
+ test(
+ "doesn't invoke the callback when the subscription has been canceled",
+ () async {
+ var controller = StreamController<void>();
+ var subscription = controller.stream
+ .transform(
+ subscriptionTransformer(
+ handlePause: expectAsync1((_) {}, count: 0),
+ ),
+ )
+ .listen(expectAsync1((_) {}, count: 0));
- subscription.cancel();
- subscription.pause();
- subscription.pause();
- subscription.pause();
- });
+ subscription.cancel();
+ subscription.pause();
+ subscription.pause();
+ subscription.pause();
+ },
+ );
});
group('with a resume callback', () {
@@ -186,11 +209,14 @@
var resumeCount = 0;
var controller = StreamController<void>();
var subscription = controller.stream
- .transform(subscriptionTransformer(
+ .transform(
+ subscriptionTransformer(
handleResume: expectAsync1((inner) {
- resumeCount++;
- inner.resume();
- }, count: 3)))
+ resumeCount++;
+ inner.resume();
+ }, count: 3),
+ ),
+ )
.listen(expectAsync1((_) {}, count: 0));
await flushMicrotasks();
@@ -218,10 +244,13 @@
var resumed = false;
var controller = StreamController<void>();
var subscription = controller.stream.transform(
- subscriptionTransformer(handleResume: expectAsync1((inner) {
- resumed = true;
- inner.resume();
- }))).listen(expectAsync1((_) {}, count: 0));
+ subscriptionTransformer(
+ handleResume: expectAsync1((inner) {
+ resumed = true;
+ inner.resume();
+ }),
+ ),
+ ).listen(expectAsync1((_) {}, count: 0));
var completer = Completer<void>();
subscription.pause(completer.future);
@@ -233,19 +262,24 @@
expect(resumed, isTrue);
});
- test("doesn't invoke the callback when the subscription has been canceled",
- () async {
- var controller = StreamController<void>();
- var subscription = controller.stream
- .transform(subscriptionTransformer(
- handlePause: expectAsync1((_) {}, count: 0)))
- .listen(expectAsync1((_) {}, count: 0));
+ test(
+ "doesn't invoke the callback when the subscription has been canceled",
+ () async {
+ var controller = StreamController<void>();
+ var subscription = controller.stream
+ .transform(
+ subscriptionTransformer(
+ handlePause: expectAsync1((_) {}, count: 0),
+ ),
+ )
+ .listen(expectAsync1((_) {}, count: 0));
- subscription.cancel();
- subscription.resume();
- subscription.resume();
- subscription.resume();
- });
+ subscription.cancel();
+ subscription.resume();
+ subscription.resume();
+ subscription.resume();
+ },
+ );
});
group('when the outer subscription is canceled but the inner is not', () {
@@ -254,10 +288,13 @@
var controller = StreamController<int>();
subscription = controller.stream
.transform(
- subscriptionTransformer(handleCancel: (_) => Future.value()))
- .listen(expectAsync1((_) {}, count: 0),
- onError: expectAsync2((_, __) {}, count: 0),
- onDone: expectAsync0(() {}, count: 0));
+ subscriptionTransformer(handleCancel: (_) => Future.value()),
+ )
+ .listen(
+ expectAsync1((_) {}, count: 0),
+ onError: expectAsync2((_, __) {}, count: 0),
+ onDone: expectAsync0(() {}, count: 0),
+ );
subscription.cancel();
controller.add(1);
controller.addError('oh no!');
diff --git a/pkgs/async/test/typed_wrapper/stream_subscription_test.dart b/pkgs/async/test/typed_wrapper/stream_subscription_test.dart
index 74195ba..5eaf8de 100644
--- a/pkgs/async/test/typed_wrapper/stream_subscription_test.dart
+++ b/pkgs/async/test/typed_wrapper/stream_subscription_test.dart
@@ -16,23 +16,29 @@
late bool isCanceled;
setUp(() {
isCanceled = false;
- controller = StreamController<Object>(onCancel: () {
- isCanceled = true;
- });
+ controller = StreamController<Object>(
+ onCancel: () {
+ isCanceled = true;
+ },
+ );
wrapper = TypeSafeStreamSubscription<int>(controller.stream.listen(null));
});
test('onData()', () {
- wrapper.onData(expectAsync1((data) {
- expect(data, equals(1));
- }));
+ wrapper.onData(
+ expectAsync1((data) {
+ expect(data, equals(1));
+ }),
+ );
controller.add(1);
});
test('onError()', () {
- wrapper.onError(expectAsync1((error) {
- expect(error, equals('oh no'));
- }));
+ wrapper.onError(
+ expectAsync1((error) {
+ expect(error, equals('oh no'));
+ }),
+ );
controller.addError('oh no');
});
@@ -73,9 +79,11 @@
late bool isCanceled;
setUp(() {
isCanceled = false;
- controller = StreamController<Object>(onCancel: () {
- isCanceled = true;
- });
+ controller = StreamController<Object>(
+ onCancel: () {
+ isCanceled = true;
+ },
+ );
wrapper = TypeSafeStreamSubscription<int>(controller.stream.listen(null));
});
@@ -85,8 +93,9 @@
// TODO(nweiz): Use the wrapper declared in setUp when sdk#26226 is
// fixed.
controller = StreamController<Object>();
- wrapper =
- TypeSafeStreamSubscription<int>(controller.stream.listen(null));
+ wrapper = TypeSafeStreamSubscription<int>(
+ controller.stream.listen(null),
+ );
wrapper.onData(expectAsync1((_) {}, count: 0));
controller.add('foo');
@@ -96,9 +105,11 @@
group("doesn't throw a TypeError for", () {
test('onError()', () {
- wrapper.onError(expectAsync1((error) {
- expect(error, equals('oh no'));
- }));
+ wrapper.onError(
+ expectAsync1((error) {
+ expect(error, equals('oh no'));
+ }),
+ );
controller.add('foo');
controller.addError('oh no');
});
diff --git a/pkgs/async/test/utils.dart b/pkgs/async/test/utils.dart
index 0a6b339..be9ad67 100644
--- a/pkgs/async/test/utils.dart
+++ b/pkgs/async/test/utils.dart
@@ -26,15 +26,16 @@
Matcher throwsZoned(Matcher matcher) => predicate((void Function() callback) {
var firstError = true;
runZonedGuarded(
- callback,
- expectAsync2((error, stackTrace) {
- if (firstError) {
- expect(error, matcher);
- firstError = false;
- } else {
- registerException(error, stackTrace);
- }
- }, max: -1));
+ callback,
+ expectAsync2((error, stackTrace) {
+ if (firstError) {
+ expect(error, matcher);
+ firstError = false;
+ } else {
+ registerException(error, stackTrace);
+ }
+ }, max: -1),
+ );
return true;
});
@@ -50,8 +51,12 @@
/// Can be used to test cases where a stream should not be used.
class UnusableStream<T> extends Stream<T> {
@override
- StreamSubscription<T> listen(void Function(T event)? onData,
- {Function? onError, void Function()? onDone, bool? cancelOnError}) {
+ StreamSubscription<T> listen(
+ void Function(T event)? onData, {
+ Function? onError,
+ void Function()? onDone,
+ bool? cancelOnError,
+ }) {
throw UnimplementedError('Gotcha!');
}
}
diff --git a/pkgs/characters/CHANGELOG.md b/pkgs/characters/CHANGELOG.md
index 29f9c4d..1992446 100644
--- a/pkgs/characters/CHANGELOG.md
+++ b/pkgs/characters/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 1.4.1-wip
+
+- Run `dart format` with the new style.
+
## 1.4.0
* Updated to use Unicode 16.0.0.
diff --git a/pkgs/characters/benchmark/benchmark.dart b/pkgs/characters/benchmark/benchmark.dart
index d1f08a3..03338a2 100644
--- a/pkgs/characters/benchmark/benchmark.dart
+++ b/pkgs/characters/benchmark/benchmark.dart
@@ -66,8 +66,10 @@
const language = '한글';
assert(language.length == 6);
var chars = Characters(hangul);
- var replaced =
- chars.replaceAll(Characters(language), Characters('Hangul!'));
+ var replaced = chars.replaceAll(
+ Characters(language),
+ Characters('Hangul!'),
+ );
count += replaced.string.length - hangul.length;
}
{
diff --git a/pkgs/characters/lib/src/characters_impl.dart b/pkgs/characters/lib/src/characters_impl.dart
index 39a3b5d..e869433 100644
--- a/pkgs/characters/lib/src/characters_impl.dart
+++ b/pkgs/characters/lib/src/characters_impl.dart
@@ -30,19 +30,26 @@
String get first => string.isEmpty
? throw StateError('No element')
: string.substring(
- 0, Breaks(string, 0, string.length, stateSoTNoBreak).nextBreak());
+ 0,
+ Breaks(string, 0, string.length, stateSoTNoBreak).nextBreak(),
+ );
@override
String get last => string.isEmpty
? throw StateError('No element')
: string.substring(
- BackBreaks(string, string.length, 0, stateEoTNoBreak).nextBreak());
+ BackBreaks(string, string.length, 0, stateEoTNoBreak).nextBreak(),
+ );
@override
String get single {
if (string.isEmpty) throw StateError('No element');
- var firstEnd =
- Breaks(string, 0, string.length, stateSoTNoBreak).nextBreak();
+ var firstEnd = Breaks(
+ string,
+ 0,
+ string.length,
+ stateSoTNoBreak,
+ ).nextBreak();
if (firstEnd == string.length) return string;
throw StateError('Too many elements');
}
@@ -80,8 +87,10 @@
}
@override
- String lastWhere(bool Function(String element) test,
- {String Function()? orElse}) {
+ String lastWhere(
+ bool Function(String element) test, {
+ String Function()? orElse,
+ }) {
var cursor = string.length;
var brk = BackBreaks(string, cursor, 0, stateEoTNoBreak);
var next = 0;
@@ -116,9 +125,12 @@
bool contains(Object? singleCharacterString) {
if (singleCharacterString is! String) return false;
if (singleCharacterString.isEmpty) return false;
- var next = Breaks(singleCharacterString, 0, singleCharacterString.length,
- stateSoTNoBreak)
- .nextBreak();
+ var next = Breaks(
+ singleCharacterString,
+ 0,
+ singleCharacterString.length,
+ stateSoTNoBreak,
+ ).nextBreak();
if (next != singleCharacterString.length) return false;
// [singleCharacterString] is single grapheme cluster.
return _indexOf(string, singleCharacterString, 0, string.length) >= 0;
@@ -443,10 +455,18 @@
StringCharacterRange(String string) : this._(string, 0, 0);
- factory StringCharacterRange.at(String string, int startIndex,
- [int? endIndex]) {
+ factory StringCharacterRange.at(
+ String string,
+ int startIndex, [
+ int? endIndex,
+ ]) {
RangeError.checkValidRange(
- startIndex, endIndex, string.length, 'startIndex', 'endIndex');
+ startIndex,
+ endIndex,
+ string.length,
+ 'startIndex',
+ 'endIndex',
+ );
return _expandRange(string, startIndex, endIndex ?? startIndex);
}
@@ -827,7 +847,10 @@
var index = _indexOf(_string, patternString, _start, _end);
if (index >= 0) {
replaced = _string.replaceRange(
- index, index + patternString.length, replacementString);
+ index,
+ index + patternString.length,
+ replacementString,
+ );
} else {
return null;
}
@@ -842,7 +865,12 @@
var replacementString = replacement.string;
if (patternString.isEmpty) {
var replaced = _explodeReplace(
- _string, _start, _end, replacementString, replacementString);
+ _string,
+ _start,
+ _end,
+ replacementString,
+ replacementString,
+ );
var newEnd = replaced.length - (_string.length - _end);
return _expandRange(replaced, _start, newEnd);
}
@@ -869,7 +897,10 @@
var replacementString = replacement.string;
var resultString = _string.replaceRange(_start, _end, replacementString);
return _expandRange(
- resultString, _start, _start + replacementString.length);
+ resultString,
+ _start,
+ _start + replacementString.length,
+ );
}
/// Expands a range if its start or end are not grapheme cluster boundaries.
@@ -1011,8 +1042,13 @@
}
}
-String _explodeReplace(String string, int start, int end,
- String internalReplacement, String outerReplacement) {
+String _explodeReplace(
+ String string,
+ int start,
+ int end,
+ String internalReplacement,
+ String outerReplacement,
+) {
if (start == end) {
return string.replaceRange(start, start, outerReplacement);
}
@@ -1052,7 +1088,11 @@
if (index > realEnd) return -1;
if (isGraphemeClusterBoundary(source, start, end, index) &&
isGraphemeClusterBoundary(
- source, start, end, index + patternLength)) {
+ source,
+ start,
+ end,
+ index + patternLength,
+ )) {
return index;
}
start = index + 1;
@@ -1094,7 +1134,11 @@
if (index < start) return -1;
if (isGraphemeClusterBoundary(source, start, end, index) &&
isGraphemeClusterBoundary(
- source, start, end, index + patternLength)) {
+ source,
+ start,
+ end,
+ index + patternLength,
+ )) {
return index;
}
realEnd = index - 1;
diff --git a/pkgs/characters/lib/src/grapheme_clusters/breaks.dart b/pkgs/characters/lib/src/grapheme_clusters/breaks.dart
index 0e69b6a..4e8c9e8 100644
--- a/pkgs/characters/lib/src/grapheme_clusters/breaks.dart
+++ b/pkgs/characters/lib/src/grapheme_clusters/breaks.dart
@@ -260,11 +260,14 @@
if (preState >= stateLookaheadRegionalEven) {
// Result is always one of one of flagBreak or flagNoBreak.
assert(
- preState == (stateLookaheadRegionalOdd | flagLookahead) ||
- preState == (stateLookaheadRegionalEven | flagLookahead),
- preState);
- assert(state == (stateRegionalEven | flagNoBreak) ||
- state == (stateRegionalOdd | flagBreak));
+ preState == (stateLookaheadRegionalOdd | flagLookahead) ||
+ preState == (stateLookaheadRegionalEven | flagLookahead),
+ preState,
+ );
+ assert(
+ state == (stateRegionalEven | flagNoBreak) ||
+ state == (stateRegionalOdd | flagBreak),
+ );
// Always reset cursor for regional lookahead.
// (Could detect stateRegionalOdd, decrease cursor two positions and
// switch to stateRegionalEven. Not worth the extra code.)
@@ -358,8 +361,11 @@
}
}
return BackBreaks(
- text, cursorBefore, start, moveBack(stateEoTNoBreak, category))
- .nextBreak();
+ text,
+ cursorBefore,
+ start,
+ moveBack(stateEoTNoBreak, category),
+ ).nextBreak();
}
return index;
}
@@ -399,18 +405,24 @@
breaks.state = stateRegionalEven;
} else {
// Was triggered by ZWJ+Pic or InCB={Extend|Linked}+InCB=Consonant.
- assert(lookbehindState == (stateLookaheadZWJPictographic | flagLookahead) ||
- lookbehindState == (stateLookaheadInC | flagLookahead) ||
- lookbehindState == (stateLookaheadInCL | flagLookahead));
+ assert(
+ lookbehindState == (stateLookaheadZWJPictographic | flagLookahead) ||
+ lookbehindState == (stateLookaheadInC | flagLookahead) ||
+ lookbehindState == (stateLookaheadInCL | flagLookahead),
+ );
// If starting in lookahead state ZWJ+Pic, and not breaking,
// final backwards state is Pic.
- assert(lookbehindState != (stateLookaheadZWJPictographic | flagLookahead) ||
- backBreaks.state == statePictographic);
+ assert(
+ lookbehindState != (stateLookaheadZWJPictographic | flagLookahead) ||
+ backBreaks.state == statePictographic,
+ );
// If starting in lookahead state InC or InCL, and not breaking,
// final backwards state is Inc.
- assert(lookbehindState != (stateLookaheadInC | flagLookahead) &&
- lookbehindState != (stateLookaheadInCL | flagLookahead) ||
- backBreaks.state == stateInC);
+ assert(
+ lookbehindState != (stateLookaheadInC | flagLookahead) &&
+ lookbehindState != (stateLookaheadInCL | flagLookahead) ||
+ backBreaks.state == stateInC,
+ );
// In both cases, that's the same as the forward state
// at the point that triggered the look-behind.
breaks.state = backBreaks.state;
diff --git a/pkgs/characters/pubspec.yaml b/pkgs/characters/pubspec.yaml
index a3de2fe..0ab15fb 100644
--- a/pkgs/characters/pubspec.yaml
+++ b/pkgs/characters/pubspec.yaml
@@ -1,5 +1,5 @@
name: characters
-version: 1.4.0
+version: 1.4.1-wip
description: >-
String replacement with operations that are Unicode/grapheme cluster aware.
repository: https://github.com/dart-lang/core/tree/main/pkgs/characters
diff --git a/pkgs/characters/test/breaks_test.dart b/pkgs/characters/test/breaks_test.dart
index b48c8cb..634b072 100644
--- a/pkgs/characters/test/breaks_test.dart
+++ b/pkgs/characters/test/breaks_test.dart
@@ -74,8 +74,11 @@
for (var i = 0; i <= input.length; i++) {
var actualBreak = nextBreak(input, 0, input.length, i);
- expect(actualBreak, nextExpectedBreak,
- reason: 'at $i: $description$kind');
+ expect(
+ actualBreak,
+ nextExpectedBreak,
+ reason: 'at $i: $description$kind',
+ );
if (i == nextExpectedBreak && i < input.length) {
nextExpectedBreak += variantParts[partCursor].length;
partCursor++;
@@ -107,8 +110,11 @@
}
}
var actualBreak = previousBreak(input, 0, input.length, i);
- expect(actualBreak, expectedBreak,
- reason: 'at $i: $description$kind');
+ expect(
+ actualBreak,
+ expectedBreak,
+ reason: 'at $i: $description$kind',
+ );
}
});
}
@@ -128,9 +134,11 @@
var nextBreak = 0;
for (var i = 0; i <= input.length; i++) {
- expect(isGraphemeClusterBoundary(input, 0, input.length, i),
- i == nextBreak,
- reason: 'at $i: $description');
+ expect(
+ isGraphemeClusterBoundary(input, 0, input.length, i),
+ i == nextBreak,
+ reason: 'at $i: $description',
+ );
if (i == nextBreak && i < input.length) {
nextBreak += variantParts[partCursor++].length;
@@ -210,8 +218,11 @@
continue;
}
// No unexpected output states.
- expect(states, contains(newState),
- reason: '($state,$c): Unexpected output state');
+ expect(
+ states,
+ contains(newState),
+ reason: '($state,$c): Unexpected output state',
+ );
// Add to fringe the first time a state is seen.
if (unreachableStates.remove(newState)) {
nextStepList.add(newState);
@@ -219,8 +230,11 @@
}
}
if (unreachableStates.isNotEmpty) {
- expect(unreachableStates.map(stateShortName).toList(), isEmpty,
- reason: 'Should be reachable');
+ expect(
+ unreachableStates.map(stateShortName).toList(),
+ isEmpty,
+ reason: 'Should be reachable',
+ );
}
if (verbose) print('Forward states reachable in $step steps');
});
@@ -273,8 +287,11 @@
break;
}
}
- expect(eqClasses, everyElement(hasLength(1)),
- reason: 'Not distinguishable in $stateCount steps');
+ expect(
+ eqClasses,
+ everyElement(hasLength(1)),
+ reason: 'Not distinguishable in $stateCount steps',
+ );
});
test('States backward reachable', () {
@@ -330,8 +347,11 @@
}
}
if (unreachableStates.isNotEmpty) {
- expect(unreachableStates.map(stateShortName).toList(), isEmpty,
- reason: 'Should be reachable, not reached in $step steps');
+ expect(
+ unreachableStates.map(stateShortName).toList(),
+ isEmpty,
+ reason: 'Should be reachable, not reached in $step steps',
+ );
}
});
@@ -349,7 +369,7 @@
// Assume that any lookahead state can be distinguished from any other
// state.
var states = [
- for (var i = 0; i < backStateLimit; i += automatonRowLength) i
+ for (var i = 0; i < backStateLimit; i += automatonRowLength) i,
];
var eqClasses = [states];
var eq = Equivalence(eqClasses);
diff --git a/pkgs/characters/test/characters_test.dart b/pkgs/characters/test/characters_test.dart
index 7dae8fa..d259cbc 100644
--- a/pkgs/characters/test/characters_test.dart
+++ b/pkgs/characters/test/characters_test.dart
@@ -70,8 +70,13 @@
var zwj = '\u200d'; // U+200D, ZWJ
var rainbow = '\u{1f308}'; // U+1F308, Rainbow. Category Pictogram
- testParts(gc('$flag$white$zwj$rainbow'), gc('$flag$white'), gc(rainbow),
- gc('$flag$zwj$rainbow'), gc('!'));
+ testParts(
+ gc('$flag$white$zwj$rainbow'),
+ gc('$flag$white'),
+ gc(rainbow),
+ gc('$flag$zwj$rainbow'),
+ gc('!'),
+ );
});
group('CharacterRange', () {
@@ -147,11 +152,7 @@
expectGC(gc(''), []);
});
group('gc-ASCII', () {
- for (var text in [
- '',
- 'A',
- '123456abcdefab',
- ]) {
+ for (var text in ['', 'A', '123456abcdefab']) {
test('"$text"', () {
expectGC(gc(text), charsOf(text));
});
@@ -162,10 +163,7 @@
});
});
group('Non-ASCII single-code point', () {
- for (var text in [
- 'à la mode',
- 'rødgrød-æble-ål',
- ]) {
+ for (var text in ['à la mode', 'rødgrød-æble-ål']) {
test('"$text"', () {
expectGC(gc(text), charsOf(text));
});
@@ -274,30 +272,50 @@
expect(actual.getRange(1, 2).toString(), expected.take(2).skip(1).join());
if (expected.isNotEmpty) {
- expect(actual.skipLast(1).toList(),
- expected.take(expected.length - 1).toList());
- expect(actual.takeLast(1).toList(),
- expected.skip(expected.length - 1).toList());
- expect(actual.skipLast(1).toString(),
- expected.take(expected.length - 1).join());
- expect(actual.takeLast(1).toString(),
- expected.skip(expected.length - 1).join());
+ expect(
+ actual.skipLast(1).toList(),
+ expected.take(expected.length - 1).toList(),
+ );
+ expect(
+ actual.takeLast(1).toList(),
+ expected.skip(expected.length - 1).toList(),
+ );
+ expect(
+ actual.skipLast(1).toString(),
+ expected.take(expected.length - 1).join(),
+ );
+ expect(
+ actual.takeLast(1).toString(),
+ expected.skip(expected.length - 1).join(),
+ );
}
bool isEven(String s) => s.length.isEven;
expect(
- actual.skipWhile(isEven).toList(), expected.skipWhile(isEven).toList());
+ actual.skipWhile(isEven).toList(),
+ expected.skipWhile(isEven).toList(),
+ );
expect(
- actual.takeWhile(isEven).toList(), expected.takeWhile(isEven).toList());
+ actual.takeWhile(isEven).toList(),
+ expected.takeWhile(isEven).toList(),
+ );
expect(
- actual.skipWhile(isEven).toString(), expected.skipWhile(isEven).join());
+ actual.skipWhile(isEven).toString(),
+ expected.skipWhile(isEven).join(),
+ );
expect(
- actual.takeWhile(isEven).toString(), expected.takeWhile(isEven).join());
+ actual.takeWhile(isEven).toString(),
+ expected.takeWhile(isEven).join(),
+ );
- expect(actual.skipLastWhile(isEven).toString(),
- expected.toList().reversed.skipWhile(isEven).toList().reversed.join());
- expect(actual.takeLastWhile(isEven).toString(),
- expected.toList().reversed.takeWhile(isEven).toList().reversed.join());
+ expect(
+ actual.skipLastWhile(isEven).toString(),
+ expected.toList().reversed.skipWhile(isEven).toList().reversed.join(),
+ );
+ expect(
+ actual.takeLastWhile(isEven).toString(),
+ expected.toList().reversed.takeWhile(isEven).toList().reversed.join(),
+ );
expect(actual.where(isEven).toString(), expected.where(isEven).join());
@@ -385,7 +403,12 @@
Characters gc(String string) => Characters(string);
void testParts(
- Characters a, Characters b, Characters c, Characters d, Characters e) {
+ Characters a,
+ Characters b,
+ Characters c,
+ Characters d,
+ Characters e,
+) {
var cs = gc('$a$b$c$d$e');
test('$cs', () {
var it = cs.iterator;
@@ -624,8 +647,12 @@
expect(range.current, '$a');
}
- expect(it.split(gc('')).map((range) => range.current),
- ['$a', '$b', '$a', '$b']);
+ expect(it.split(gc('')).map((range) => range.current), [
+ '$a',
+ '$b',
+ '$a',
+ '$b',
+ ]);
expect(gc('').iterator.split(gc('')).map((range) => range.current), ['']);
@@ -757,9 +784,12 @@
final Characters hant = gc('\u11a8'); // Hangul T, Jongseong Kiyeok.
final Characters hanlv = gc('\uac00'); // Hangul LV, Syllable Ga.
final Characters hanlvt = gc('\uac01'); // Hangul LVT, Syllable Gag.
-final Characters inc =
- gc('\u0915'); // Other{InCL=Consonant}, Devanagari letter Ka.
-final Characters ine =
- gc('\u0300'); // Extend{InCL=Extend}, Combining Grave Accent.
-final Characters inl =
- gc('\u094d'); // Extend{InCL=Linker}, Devanagari Sign Virama.
+final Characters inc = gc(
+ '\u0915',
+); // Other{InCL=Consonant}, Devanagari letter Ka.
+final Characters ine = gc(
+ '\u0300',
+); // Extend{InCL=Extend}, Combining Grave Accent.
+final Characters inl = gc(
+ '\u094d',
+); // Extend{InCL=Linker}, Devanagari Sign Virama.
diff --git a/pkgs/characters/test/src/equiv.dart b/pkgs/characters/test/src/equiv.dart
index 705167e..9a2afd1 100644
--- a/pkgs/characters/test/src/equiv.dart
+++ b/pkgs/characters/test/src/equiv.dart
@@ -35,9 +35,10 @@
/// if [allowCollapse] is `false` an error is raised, and
/// If [allowCollapse] is `true` the equivalence classes are
/// collapsed.
- Equivalence(Iterable<Iterable<T>> equivalenceClasses,
- {bool allowCollapse = false})
- : _equivalences = [],
+ Equivalence(
+ Iterable<Iterable<T>> equivalenceClasses, {
+ bool allowCollapse = false,
+ }) : _equivalences = [],
_class = {} {
for (var eqClass in equivalenceClasses) {
var newClass = _equivalences.length;
@@ -49,8 +50,11 @@
} else if (existing != newClass) {
if (!allowCollapse) {
// Wasn't in the *same* iterable.
- throw ArgumentError.value(equivalenceClasses, 'equivalenceClasses',
- "Contains element '$element' more than once");
+ throw ArgumentError.value(
+ equivalenceClasses,
+ 'equivalenceClasses',
+ "Contains element '$element' more than once",
+ );
}
var c1 = _canonicalizeId(existing);
var c2 = _canonicalizeId(newClass);
diff --git a/pkgs/characters/test/src/unicode_tests.dart b/pkgs/characters/test/src/unicode_tests.dart
index f88ba26..5c01dda 100644
--- a/pkgs/characters/test/src/unicode_tests.dart
+++ b/pkgs/characters/test/src/unicode_tests.dart
@@ -20,8 +20,10 @@
/// can be compared to the original tests.)
String testDescription(List<String> expected) {
var expectedString = expected
- .map((s) =>
- s.runes.map((x) => x.toRadixString(16).padLeft(4, '0')).join(' × '))
+ .map(
+ (s) =>
+ s.runes.map((x) => x.toRadixString(16).padLeft(4, '0')).join(' × '),
+ )
.join(' ÷ ');
return '÷ $expectedString ÷';
}
diff --git a/pkgs/characters/test/src/various_tests.dart b/pkgs/characters/test/src/various_tests.dart
index 7409c5b..643facc 100644
--- a/pkgs/characters/test/src/various_tests.dart
+++ b/pkgs/characters/test/src/various_tests.dart
@@ -9,6 +9,6 @@
'L̠ͨͧͩ͘',
'G̴̻͈͍͔̹̑͗̎̅͛́',
'Ǫ̵̹̻̝̳͂̌̌͘',
- '!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞'
+ '!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞',
],
];
diff --git a/pkgs/characters/tool/benchmark.dart b/pkgs/characters/tool/benchmark.dart
index fd1170b..a77b811 100644
--- a/pkgs/characters/tool/benchmark.dart
+++ b/pkgs/characters/tool/benchmark.dart
@@ -34,8 +34,10 @@
}
print('gc: Grapheme Clusters, cp: Code Points, cu: Code Units.');
if (gcsf != gcsb) {
- print('ERROR: Did not count the same number of grapheme clusters: '
- '$gcsf forward vs. $gcsb backward.');
+ print(
+ 'ERROR: Did not count the same number of grapheme clusters: '
+ '$gcsf forward vs. $gcsb backward.',
+ );
} else {
print('Total: $gcsf gc, $codePoints cp, $codeUnits cu');
print('Avg ${(codePoints / gcsf).toStringAsFixed(3)} cp/gc');
@@ -59,10 +61,12 @@
e = sw.elapsedMilliseconds;
n++;
} while (e < 2000);
- print('Forward #$i: ${(gc / e).round()} gc/ms, '
- '${(n * cp / e).round()} cp/ms, '
- '${(n * cu / e).round()} cu/ms, '
- '$n rounds');
+ print(
+ 'Forward #$i: ${(gc / e).round()} gc/ms, '
+ '${(n * cp / e).round()} cp/ms, '
+ '${(n * cu / e).round()} cu/ms, '
+ '$n rounds',
+ );
return gc ~/ n;
}
@@ -79,9 +83,11 @@
e = sw.elapsedMilliseconds;
n++;
} while (e < 2000);
- print('Backward #$i: ${(gc / e).round()} gc/ms, '
- '${(n * cp / e).round()} cp/ms, '
- '${(n * cu / e).round()} cu/ms, '
- '$n rounds');
+ print(
+ 'Backward #$i: ${(gc / e).round()} gc/ms, '
+ '${(n * cp / e).round()} cp/ms, '
+ '${(n * cu / e).round()} cu/ms, '
+ '$n rounds',
+ );
return gc ~/ n;
}
diff --git a/pkgs/characters/tool/bin/generate_tables.dart b/pkgs/characters/tool/bin/generate_tables.dart
index 709fd08..f348276 100644
--- a/pkgs/characters/tool/bin/generate_tables.dart
+++ b/pkgs/characters/tool/bin/generate_tables.dart
@@ -84,11 +84,18 @@
}
}
- var categories =
- await loadCategories(update: flags.update, verbose: flags.verbose);
+ var categories = await loadCategories(
+ update: flags.update,
+ verbose: flags.verbose,
+ );
- generateTables(output, categories,
- dryrun: flags.dryrun, verbose: flags.verbose, optimize: flags.optimize);
+ generateTables(
+ output,
+ categories,
+ dryrun: flags.dryrun,
+ verbose: flags.verbose,
+ optimize: flags.optimize,
+ );
}
void generateTables(
@@ -103,7 +110,10 @@
var highChunkSize = defaultHighChunkSize;
int optimizeTable(
- IndirectTable chunkTable, int lowChunkSize, int highChunkSize) {
+ IndirectTable chunkTable,
+ int lowChunkSize,
+ int highChunkSize,
+ ) {
var index = 0;
do {
chunkTable.entries.add(TableEntry(0, index, lowChunkSize));
@@ -115,22 +125,26 @@
index += highChunkSize;
} while (index < 0x110000);
var highChunkCount = chunkTable.entries.length - lowChunkCount;
- assert(lowChunkCount * lowChunkSize + highChunkCount * highChunkSize ==
- 0x110000);
+ assert(
+ lowChunkCount * lowChunkSize + highChunkCount * highChunkSize == 0x110000,
+ );
assert(chunkTable.chunks.length == 1);
- assert(_validate(table, chunkTable, lowChunkSize, highChunkSize,
- verbose: false));
+ assert(
+ _validate(table, chunkTable, lowChunkSize, highChunkSize, verbose: false),
+ );
chunkifyTable(chunkTable);
assert(chunkTable.entries.length == lowChunkCount + highChunkCount);
- assert(_validate(table, chunkTable, lowChunkSize, highChunkSize,
- verbose: false));
+ assert(
+ _validate(table, chunkTable, lowChunkSize, highChunkSize, verbose: false),
+ );
combineChunkedTable(chunkTable);
assert(chunkTable.entries.length == lowChunkCount + highChunkCount);
assert(chunkTable.chunks.length == 1);
- assert(_validate(table, chunkTable, lowChunkSize, highChunkSize,
- verbose: false));
+ assert(
+ _validate(table, chunkTable, lowChunkSize, highChunkSize, verbose: false),
+ );
var size = chunkTable.chunks[0].length + chunkTable.entries.length * 2;
return size;
@@ -153,9 +167,11 @@
var newSize = optimizeTable(newChunk, low, high);
if (verbose) {
var delta = newSize - size;
- stderr.writeln("${size < newSize ? "Worse" : "Better"}"
- ' chunk size: $low/$high: $newSize '
- "(${delta > 0 ? "+$delta" : delta})");
+ stderr.writeln(
+ "${size < newSize ? "Worse" : "Better"}"
+ ' chunk size: $low/$high: $newSize '
+ "(${delta > 0 ? "+$delta" : delta})",
+ );
}
if (newSize < size) {
lowChunkSize = low;
@@ -173,12 +189,20 @@
}
var buffer = StringBuffer();
- writeHeader(
- buffer, [graphemeTestData, emojiTestData, graphemeBreakPropertyData]);
+ writeHeader(buffer, [
+ graphemeTestData,
+ emojiTestData,
+ graphemeBreakPropertyData,
+ ]);
buffer.writeln();
- writeTables(buffer, chunkTable, lowChunkSize, highChunkSize,
- verbose: verbose);
+ writeTables(
+ buffer,
+ chunkTable,
+ lowChunkSize,
+ highChunkSize,
+ verbose: verbose,
+ );
writeForwardAutomaton(buffer, verbose: verbose);
buffer.writeln();
@@ -195,21 +219,38 @@
// -----------------------------------------------------------------------------
// Combined table writing.
void writeTables(
- StringSink out, IndirectTable table, int lowChunkSize, int highChunkSize,
- {required bool verbose}) {
+ StringSink out,
+ IndirectTable table,
+ int lowChunkSize,
+ int highChunkSize, {
+ required bool verbose,
+}) {
assert(table.chunks.length == 1);
_writeStringLiteral(out, '_data', table.chunks[0], verbose: verbose);
- _writeStringLiteral(out, '_start', table.entries.map((e) => e.start).toList(),
- verbose: verbose);
+ _writeStringLiteral(
+ out,
+ '_start',
+ table.entries.map((e) => e.start).toList(),
+ verbose: verbose,
+ );
_writeLookupFunction(out, '_data', '_start', lowChunkSize);
out.writeln();
_writeSurrogateLookupFunction(
- out, '_data', '_start', 65536 ~/ lowChunkSize, highChunkSize);
+ out,
+ '_data',
+ '_start',
+ 65536 ~/ lowChunkSize,
+ highChunkSize,
+ );
out.writeln();
}
-void _writeStringLiteral(StringSink out, String name, List<int> data,
- {required bool verbose}) {
+void _writeStringLiteral(
+ StringSink out,
+ String name,
+ List<int> data, {
+ required bool verbose,
+}) {
var prefix = 'const String $name = ';
out.write(prefix);
var writer = StringLiteralWriter(out, padding: 4, escape: _needsEscape);
@@ -231,18 +272,38 @@
codeUnit > 0xff || codeUnit == 0x7f || codeUnit & 0x60 == 0;
void _writeLookupFunction(
- StringSink out, String dataName, String startName, int chunkSize) {
+ StringSink out,
+ String dataName,
+ String startName,
+ int chunkSize,
+) {
out.write(_lookupMethod('low', dataName, startName, chunkSize));
}
-void _writeSurrogateLookupFunction(StringSink out, String dataName,
- String startName, int startOffset, int chunkSize) {
- out.write(_lookupSurrogatesMethod(
- 'high', dataName, startName, startOffset, chunkSize));
+void _writeSurrogateLookupFunction(
+ StringSink out,
+ String dataName,
+ String startName,
+ int startOffset,
+ int chunkSize,
+) {
+ out.write(
+ _lookupSurrogatesMethod(
+ 'high',
+ dataName,
+ startName,
+ startOffset,
+ chunkSize,
+ ),
+ );
}
String _lookupMethod(
- String name, String dataName, String startName, int chunkSize) =>
+ String name,
+ String dataName,
+ String startName,
+ int chunkSize,
+) =>
'''
$preferInline
int $name(int codeUnit) {
@@ -252,8 +313,13 @@
}
''';
-String _lookupSurrogatesMethod(String name, String dataName, String startName,
- int startOffset, int chunkSize) {
+String _lookupSurrogatesMethod(
+ String name,
+ String dataName,
+ String startName,
+ int startOffset,
+ int chunkSize,
+) {
if (chunkSize == 1024) {
return '''
$preferInline
@@ -278,9 +344,13 @@
}
// -----------------------------------------------------------------------------
-bool _validate(Uint8List table, IndirectTable indirectTable, int lowChunkSize,
- int highChunkSize,
- {required bool verbose}) {
+bool _validate(
+ Uint8List table,
+ IndirectTable indirectTable,
+ int lowChunkSize,
+ int highChunkSize, {
+ required bool verbose,
+}) {
var lowChunkCount = 65536 ~/ lowChunkSize;
var lowChunkShift = lowChunkSize.bitLength - 1;
var lowChunkMask = lowChunkSize - 1;
@@ -292,8 +362,10 @@
[entry.start + (i & lowChunkMask)];
if (value != indirectValue) {
stderr.writeln('$entryIndex: $entry');
- stderr.writeln('Error: ${i.toRadixString(16)} -> Expected $value,'
- ' was $indirectValue');
+ stderr.writeln(
+ 'Error: ${i.toRadixString(16)} -> Expected $value,'
+ ' was $indirectValue',
+ );
printIndirectTable(indirectTable);
return false;
}
@@ -309,8 +381,10 @@
[entry.start + (j & highChunkMask)];
if (value != indirectValue) {
stderr.writeln('$entryIndex: $entry');
- stderr.writeln('Error: ${i.toRadixString(16)} -> Expected $value,'
- ' was $indirectValue');
+ stderr.writeln(
+ 'Error: ${i.toRadixString(16)} -> Expected $value,'
+ ' was $indirectValue',
+ );
printIndirectTable(indirectTable);
return false;
}
@@ -322,6 +396,8 @@
}
void printIndirectTable(IndirectTable table) {
- stderr.writeln("IT(chunks: ${table.chunks.map((x) => "#${x.length}")},"
- ' entries: ${table.entries}');
+ stderr.writeln(
+ "IT(chunks: ${table.chunks.map((x) => "#${x.length}")},"
+ ' entries: ${table.entries}',
+ );
}
diff --git a/pkgs/characters/tool/bin/generate_tests.dart b/pkgs/characters/tool/bin/generate_tests.dart
index 2f3b67b..71f7860 100644
--- a/pkgs/characters/tool/bin/generate_tests.dart
+++ b/pkgs/characters/tool/bin/generate_tests.dart
@@ -46,22 +46,32 @@
var (categories, graphemeTests, emojiTests) = await (
loadCategories(update: flags.update, verbose: flags.verbose),
graphemeTestData.load(checkForUpdate: flags.update),
- emojiTestData.load(checkForUpdate: flags.update)
+ emojiTestData.load(checkForUpdate: flags.update),
).wait;
- generateTests(output, [graphemeTests, emojiTests], categories,
- verbose: flags.verbose, dryrun: flags.dryrun);
+ generateTests(
+ output,
+ [graphemeTests, emojiTests],
+ categories,
+ verbose: flags.verbose,
+ dryrun: flags.dryrun,
+ );
}
-void generateTests(File? output, List<String> texts, Uint8List categories,
- {bool verbose = false, bool dryrun = false}) {
+void generateTests(
+ File? output,
+ List<String> texts,
+ Uint8List categories, {
+ bool verbose = false,
+ bool dryrun = false,
+}) {
var buffer = StringBuffer();
writeHeader(buffer, [
graphemeTestData,
emojiTestData,
graphemeBreakPropertyData,
emojiData,
- derivedData
+ derivedData,
]);
buffer.writeln('// ignore_for_file: lines_longer_than_80_chars');
buffer.writeln('// dart format off');
@@ -72,8 +82,15 @@
// Example character of a category which is in the lower planes.
var lowerChars = List<int>.filled(inputCategoryCount, -1);
- writeTests(buffer, texts, categories, lowerChars, upperChars,
- verbose: verbose, dryrun: dryrun);
+ writeTests(
+ buffer,
+ texts,
+ categories,
+ lowerChars,
+ upperChars,
+ verbose: verbose,
+ dryrun: dryrun,
+ );
buffer.writeln('// dart format on');
@@ -86,9 +103,15 @@
}
}
-void writeTests(StringSink buffer, List<String> texts, Uint8List categories,
- List<int> lowerChars, List<int> upperChars,
- {bool dryrun = false, bool verbose = defaultVerbose}) async {
+void writeTests(
+ StringSink buffer,
+ List<String> texts,
+ Uint8List categories,
+ List<int> lowerChars,
+ List<int> upperChars, {
+ bool dryrun = false,
+ bool verbose = defaultVerbose,
+}) async {
var writer = StringLiteralWriter(buffer, lineLength: 9999, escape: _escape);
void writeParts(List<List<int>> parts, String description) {
buffer.writeln(' [');
@@ -167,8 +190,12 @@
..writeln(' = [');
}
-void writeOtherCategories(StringSink output, Uint8List categories,
- List<int> lowerChars, List<int> upperChars) {
+void writeOtherCategories(
+ StringSink output,
+ Uint8List categories,
+ List<int> lowerChars,
+ List<int> upperChars,
+) {
var otherCategories = lowerChars;
for (var i = 0; i < 0x110000; i++) {
if (i == 0x10000) otherCategories = upperChars;
diff --git a/pkgs/characters/tool/generate.dart b/pkgs/characters/tool/generate.dart
index 2eadd33..8536d83 100644
--- a/pkgs/characters/tool/generate.dart
+++ b/pkgs/characters/tool/generate.dart
@@ -16,8 +16,12 @@
/// Use this tool for updates, and only access `bin/generate_tables.dart` and
/// `bin/generate_tests.dart` directly during development of those files.
void main(List<String> args) async {
- var flags =
- parseArgs(args, 'generate', allowOptimize: true, allowFile: false);
+ var flags = parseArgs(
+ args,
+ 'generate',
+ allowOptimize: true,
+ allowFile: false,
+ );
if (flags.update && !await checkLicense(flags.acceptLicenseChange)) {
stderr.writeln('EXITING');
exit(1);
@@ -29,12 +33,21 @@
emojiData.load(checkForUpdate: flags.update),
).wait;
- generateTables(File(path(packageRoot, tableFile)), categories,
- optimize: flags.optimize, dryrun: flags.dryrun, verbose: flags.verbose);
+ generateTables(
+ File(path(packageRoot, tableFile)),
+ categories,
+ optimize: flags.optimize,
+ dryrun: flags.dryrun,
+ verbose: flags.verbose,
+ );
- generateTests(File(path(packageRoot, testFile)), [graphemeTests, emojiTests],
- categories,
- dryrun: flags.dryrun, verbose: flags.verbose);
+ generateTests(
+ File(path(packageRoot, testFile)),
+ [graphemeTests, emojiTests],
+ categories,
+ dryrun: flags.dryrun,
+ verbose: flags.verbose,
+ );
if (flags.update && !flags.dryrun) {
var version = guessVersion(await graphemeBreakPropertyData.contents);
diff --git a/pkgs/characters/tool/src/args.dart b/pkgs/characters/tool/src/args.dart
index 73b6c5e..db42642 100644
--- a/pkgs/characters/tool/src/args.dart
+++ b/pkgs/characters/tool/src/args.dart
@@ -15,8 +15,12 @@
File? targetFile,
});
-Flags parseArgs(List<String> args, String toolName,
- {bool allowOptimize = false, bool allowFile = true}) {
+Flags parseArgs(
+ List<String> args,
+ String toolName, {
+ bool allowOptimize = false,
+ bool allowFile = true,
+}) {
var update = false;
var dryrun = false;
var verbose = false;
@@ -27,16 +31,19 @@
if (arg == '-h' || arg == '--help') {
stderr
..writeln(
- "Usage: $toolName.dart [-u] ${allowOptimize ? "[-i|-o] " : ""}[-n]"
- "${allowFile ? " <targetFile>" : ""}")
+ "Usage: $toolName.dart [-u] ${allowOptimize ? "[-i|-o] " : ""}[-n]"
+ "${allowFile ? " <targetFile>" : ""}",
+ )
..writeln('-h | --help : Print this help and exit')
..writeln('-u | --update : Fetch new data files')
..writeln('--accept-license : Accept a changed license')
..writeln(
- '-n | --dryrun : Write to stdout instead of target file');
+ '-n | --dryrun : Write to stdout instead of target file',
+ );
if (allowOptimize) {
stderr.writeln(
- '-o | -i | --optimize : Optimize size parameters for tables');
+ '-o | -i | --optimize : Optimize size parameters for tables',
+ );
}
stderr.writeln('-v | --verbose : Print more information');
if (allowFile) {
diff --git a/pkgs/characters/tool/src/atsp.dart b/pkgs/characters/tool/src/atsp.dart
index 5141caf..43d67bc 100644
--- a/pkgs/characters/tool/src/atsp.dart
+++ b/pkgs/characters/tool/src/atsp.dart
@@ -113,7 +113,7 @@
wFDEBCA,
wFDECBA,
wFEDBCA,
- wFEDCBA
+ wFEDCBA,
]);
if (best < wABCDEF) {
// Reorder and reverse to match the (or a) best solution.
diff --git a/pkgs/characters/tool/src/automaton_builder.dart b/pkgs/characters/tool/src/automaton_builder.dart
index f8099e0..2dd0792 100644
--- a/pkgs/characters/tool/src/automaton_builder.dart
+++ b/pkgs/characters/tool/src/automaton_builder.dart
@@ -61,22 +61,28 @@
void writeForwardAutomaton(StringSink buffer, {required bool verbose}) {
assert(categories.length == categoryCount);
- assert(automatonRowLength & maskFlags == 0 &&
- automatonRowLength >= categoryCount);
+ assert(
+ automatonRowLength & maskFlags == 0 && automatonRowLength >= categoryCount,
+ );
var table = Uint16List(stateLimit);
void transitionLA(int state, int category, int targetState, int flags) {
assert(flags <= maskFlags);
assert(
- flags != flagLookahead || targetState >= stateLookaheadMin,
- '${stateShortName(state)} x ${categoryNames[category]} -> '
- '${_targetStateName(targetState, flags)} | $flags');
+ flags != flagLookahead || targetState >= stateLookaheadMin,
+ '${stateShortName(state)} x ${categoryNames[category]} -> '
+ '${_targetStateName(targetState, flags)} | $flags',
+ );
table[state + category] = targetState + flags;
}
void transition(int state, int category, int targetState, bool breakBefore) {
assert(targetState < stateLimit, '$state + $category -> $targetState');
transitionLA(
- state, category, targetState, breakBefore ? flagBreak : flagNoBreak);
+ state,
+ category,
+ targetState,
+ breakBefore ? flagBreak : flagNoBreak,
+ );
}
for (var state = 0; state < stateLimit; state += automatonRowLength) {
@@ -102,13 +108,25 @@
if (state == stateCZWJ || state == stateCIE || state == stateCZIE) {
transitionLA(
- state, categoryOtherIndicConsonant, stateLookaheadInC, flagLookahead);
+ state,
+ categoryOtherIndicConsonant,
+ stateLookaheadInC,
+ flagLookahead,
+ );
} else if (state == stateCIL || state == stateCILZ || state == stateCZIL) {
- transitionLA(state, categoryOtherIndicConsonant, stateLookaheadInCL,
- flagLookahead);
+ transitionLA(
+ state,
+ categoryOtherIndicConsonant,
+ stateLookaheadInCL,
+ flagLookahead,
+ );
} else {
- transition(state, categoryOtherIndicConsonant, stateInC,
- !(neverBreakBefore || state == stateInCL || state == stateCAny));
+ transition(
+ state,
+ categoryOtherIndicConsonant,
+ stateInC,
+ !(neverBreakBefore || state == stateInCL || state == stateCAny),
+ );
}
// CR.
// GB4 + GB5. Always break, after unless followed by LF, so remember
@@ -117,8 +135,12 @@
// LF.
// GB3 + GB4 + GB5. Always break after. Break before unless following CR.
- transition(state, categoryLF, stateBreak,
- state != stateCR && state != stateSoTNoBreak);
+ transition(
+ state,
+ categoryLF,
+ stateBreak,
+ state != stateCR && state != stateSoTNoBreak,
+ );
// Control. (Like CR+LF, without their mutual exception.)
// GB4 + GB5. Always break before, even after Prepend,
@@ -155,9 +177,17 @@
// break before only if required by GB1-GB5.
transition(state, categoryExtend, stateOther, alwaysBreakBefore);
transition(
- state, categoryExtendIndicExtend, stateOther, alwaysBreakBefore);
+ state,
+ categoryExtendIndicExtend,
+ stateOther,
+ alwaysBreakBefore,
+ );
transition(
- state, categoryExtendIndicLinked, stateOther, alwaysBreakBefore);
+ state,
+ categoryExtendIndicLinked,
+ stateOther,
+ alwaysBreakBefore,
+ );
transition(state, categoryZWJ, stateOther, alwaysBreakBefore);
} else {
transition(
@@ -177,15 +207,16 @@
},
false);
transition(
- state,
- categoryExtend,
- (state == stateCAny ||
- state == stateCIE ||
- state == stateCIL ||
- state == stateCExt)
- ? stateCExt
- : stateOther,
- false);
+ state,
+ categoryExtend,
+ (state == stateCAny ||
+ state == stateCIE ||
+ state == stateCIL ||
+ state == stateCExt)
+ ? stateCExt
+ : stateOther,
+ false,
+ );
transition(
state,
categoryExtendIndicExtend,
@@ -228,12 +259,20 @@
} else if (state == stateCAny) {
transition(state, categoryRegionalIndicator, stateCReg, false);
} else if (state == stateCReg) {
- transitionLA(state, categoryRegionalIndicator, stateLookaheadRegionalEven,
- flagLookahead);
+ transitionLA(
+ state,
+ categoryRegionalIndicator,
+ stateLookaheadRegionalEven,
+ flagLookahead,
+ );
} else {
// Break unless prior state says not to.
- transition(state, categoryRegionalIndicator, stateRegionalSingle,
- !neverBreakBefore);
+ transition(
+ state,
+ categoryRegionalIndicator,
+ stateRegionalSingle,
+ !neverBreakBefore,
+ );
}
// Prepend.
@@ -248,36 +287,65 @@
// GB6+GB7+GB8.
// Don't break if T follows V and V follows L.
transition(
- state, categoryL, stateL, !(neverBreakBefore || state == stateL));
+ state,
+ categoryL,
+ stateL,
+ !(neverBreakBefore || state == stateL),
+ );
transition(
- state, categoryLV, stateV, !(neverBreakBefore || state == stateL));
+ state,
+ categoryLV,
+ stateV,
+ !(neverBreakBefore || state == stateL),
+ );
transition(
- state, categoryLVT, stateT, !(neverBreakBefore || state == stateL));
- transition(state, categoryV, stateV,
- !(neverBreakBefore || state == stateL || state == stateV));
- transition(state, categoryT, stateT,
- !(neverBreakBefore || state == stateV || state == stateT));
+ state,
+ categoryLVT,
+ stateT,
+ !(neverBreakBefore || state == stateL),
+ );
+ transition(
+ state,
+ categoryV,
+ stateV,
+ !(neverBreakBefore || state == stateL || state == stateV),
+ );
+ transition(
+ state,
+ categoryT,
+ stateT,
+ !(neverBreakBefore || state == stateV || state == stateT),
+ );
// Emoji
// GB11.
if (state == stateCZWJ ||
state == stateCExZ ||
state == stateCIEZ ||
state == stateCILZ) {
- transitionLA(state, categoryPictographic, stateLookaheadZWJPictographic,
- flagLookahead);
+ transitionLA(
+ state,
+ categoryPictographic,
+ stateLookaheadZWJPictographic,
+ flagLookahead,
+ );
} else {
transition(
- state,
- categoryPictographic,
- statePictographic,
- state != statePrepend &&
- state != statePictographicZWJ &&
- state != stateSoTNoBreak);
+ state,
+ categoryPictographic,
+ statePictographic,
+ state != statePrepend &&
+ state != statePictographicZWJ &&
+ state != stateSoTNoBreak,
+ );
}
// End of input.
// GB2.
- transition(state, categoryEoT, stateSoTNoBreak,
- state != stateSoT && state != stateSoTNoBreak && state != stateCAny);
+ transition(
+ state,
+ categoryEoT,
+ stateSoTNoBreak,
+ state != stateSoT && state != stateSoTNoBreak && state != stateCAny,
+ );
// Pad table if necessary.
for (var c = categoryCount; c < automatonRowLength; c++) {
@@ -428,8 +496,10 @@
assert(categories.length <= automatonRowLength);
var table = Uint16List(backStateLimit);
void transitionLA(int state, int category, int targetState, int flags) {
- assert(state < backStateLimit && targetState < backStateLimit,
- '$state + $category -> $targetState');
+ assert(
+ state < backStateLimit && targetState < backStateLimit,
+ '$state + $category -> $targetState',
+ );
assert(
switch ((state, targetState)) {
(< stateLookaheadMin, < stateLookaheadMin) => flags < flagLookahead,
@@ -447,7 +517,11 @@
void transition(int state, int category, int targetState, bool breakBefore) {
assert(state < stateLookaheadMin && targetState < stateLookaheadMin);
transitionLA(
- state, category, targetState, (breakBefore ? flagBreak : flagNoBreak));
+ state,
+ category,
+ targetState,
+ (breakBefore ? flagBreak : flagNoBreak),
+ );
}
for (var state in backStates) {
@@ -463,13 +537,25 @@
// Remaining inputs are unreachable.
continue;
}
- transition(state, categoryOther, stateOther,
- state != stateExtend && state != stateEoTNoBreak);
- transition(state, categoryOtherIndicConsonant, stateInC,
- state != stateExtend && state != stateEoTNoBreak);
+ transition(
+ state,
+ categoryOther,
+ stateOther,
+ state != stateExtend && state != stateEoTNoBreak,
+ );
+ transition(
+ state,
+ categoryOtherIndicConsonant,
+ stateInC,
+ state != stateExtend && state != stateEoTNoBreak,
+ );
transition(state, categoryLF, stateLF, state != stateEoTNoBreak);
- transition(state, categoryCR, stateBreak,
- state != stateLF && state != stateEoTNoBreak);
+ transition(
+ state,
+ categoryCR,
+ stateBreak,
+ state != stateLF && state != stateEoTNoBreak,
+ );
transition(state, categoryControl, stateBreak, state != stateEoTNoBreak);
var breakBeforeExtend = state != stateExtend &&
@@ -478,81 +564,141 @@
transition(state, categoryExtend, stateExtend, breakBeforeExtend);
if (state != stateInC) {
transition(
- state, categoryExtendIndicExtend, stateExtend, breakBeforeExtend);
+ state,
+ categoryExtendIndicExtend,
+ stateExtend,
+ breakBeforeExtend,
+ );
transition(
- state, categoryExtendIndicLinked, stateExtend, breakBeforeExtend);
+ state,
+ categoryExtendIndicLinked,
+ stateExtend,
+ breakBeforeExtend,
+ );
} else {
// If these come just before an InCB Consonant, look ahead.
transitionLA(
- state, categoryExtendIndicExtend, stateLookaheadInC, flagLookahead);
- transitionLA(state, categoryExtendIndicLinked, stateLookaheadInCL,
- flagLookahead);
+ state,
+ categoryExtendIndicExtend,
+ stateLookaheadInC,
+ flagLookahead,
+ );
+ transitionLA(
+ state,
+ categoryExtendIndicLinked,
+ stateLookaheadInCL,
+ flagLookahead,
+ );
}
- transition(state, categorySpacingMark, stateExtend,
- state != stateExtend && state != stateEoTNoBreak);
+ transition(
+ state,
+ categorySpacingMark,
+ stateExtend,
+ state != stateExtend && state != stateEoTNoBreak,
+ );
if (state == statePictographic) {
// Break-before value has no effect on lookahead states.
transitionLA(
- state, categoryZWJ, stateLookaheadZWJPictographic, flagLookahead);
+ state,
+ categoryZWJ,
+ stateLookaheadZWJPictographic,
+ flagLookahead,
+ );
} else if (state == stateInC) {
transitionLA(state, categoryZWJ, stateLookaheadInC, flagLookahead);
} else {
- transition(state, categoryZWJ, stateExtend,
- state != stateExtend && state != stateEoTNoBreak);
+ transition(
+ state,
+ categoryZWJ,
+ stateExtend,
+ state != stateExtend && state != stateEoTNoBreak,
+ );
}
if (state == stateRegionalEven) {
transition(state, categoryRegionalIndicator, stateRegionalOdd, true);
} else if (state == stateRegionalSingle) {
- transitionLA(state, categoryRegionalIndicator,
- stateLookaheadRegionalEven, flagLookahead);
+ transitionLA(
+ state,
+ categoryRegionalIndicator,
+ stateLookaheadRegionalEven,
+ flagLookahead,
+ );
} else {
- transition(state, categoryRegionalIndicator, stateRegionalSingle,
- state != stateExtend && state != stateEoTNoBreak);
+ transition(
+ state,
+ categoryRegionalIndicator,
+ stateRegionalSingle,
+ state != stateExtend && state != stateEoTNoBreak,
+ );
}
- transition(state, categoryPrepend, stateOther,
- state == stateBreak || state == stateCR || state == stateEoT);
transition(
- state,
- categoryL,
- stateL,
- state != stateExtend &&
- state != stateL &&
- state != stateV &&
- state != stateEoTNoBreak);
+ state,
+ categoryPrepend,
+ stateOther,
+ state == stateBreak || state == stateCR || state == stateEoT,
+ );
transition(
- state,
- categoryLV,
- stateL,
- state != stateExtend &&
- state != stateV &&
- state != stateT &&
- state != stateEoTNoBreak);
- transition(state, categoryLVT, stateL,
- state != stateExtend && state != stateT && state != stateEoTNoBreak);
+ state,
+ categoryL,
+ stateL,
+ state != stateExtend &&
+ state != stateL &&
+ state != stateV &&
+ state != stateEoTNoBreak,
+ );
transition(
- state,
- categoryV,
- stateV,
- state != stateExtend &&
- state != stateT &&
- state != stateV &&
- state != stateEoTNoBreak);
- transition(state, categoryT, stateT,
- state != stateExtend && state != stateT && state != stateEoTNoBreak);
+ state,
+ categoryLV,
+ stateL,
+ state != stateExtend &&
+ state != stateV &&
+ state != stateT &&
+ state != stateEoTNoBreak,
+ );
transition(
- state,
- categoryPictographic,
- statePictographic,
- state != stateExtend &&
- state != stateRegionalOdd &&
- state != stateEoTNoBreak);
+ state,
+ categoryLVT,
+ stateL,
+ state != stateExtend && state != stateT && state != stateEoTNoBreak,
+ );
+ transition(
+ state,
+ categoryV,
+ stateV,
+ state != stateExtend &&
+ state != stateT &&
+ state != stateV &&
+ state != stateEoTNoBreak,
+ );
+ transition(
+ state,
+ categoryT,
+ stateT,
+ state != stateExtend && state != stateT && state != stateEoTNoBreak,
+ );
+ transition(
+ state,
+ categoryPictographic,
+ statePictographic,
+ state != stateExtend &&
+ state != stateRegionalOdd &&
+ state != stateEoTNoBreak,
+ );
// Use EoT-NoBreak as marker for unreachable.
- transition(state, categorySoT, stateEoTNoBreak,
- state != stateEoT && state != stateEoTNoBreak);
+ transition(
+ state,
+ categorySoT,
+ stateEoTNoBreak,
+ state != stateEoT && state != stateEoTNoBreak,
+ );
} else {
if (state == stateLookaheadRegionalEven) {
transitionLA(
- state, categoryRegionalIndicator, stateLookaheadRegionalOdd, 0);
+ state,
+ categoryRegionalIndicator,
+ stateLookaheadRegionalOdd,
+ 0,
+ );
for (var c = 0; c < categoryCount; c++) {
if (c != categoryRegionalIndicator) {
transitionLA(state, c, stateRegionalEven, 0);
@@ -562,7 +708,11 @@
}
if (state == stateLookaheadRegionalOdd) {
transitionLA(
- state, categoryRegionalIndicator, stateLookaheadRegionalEven, 0);
+ state,
+ categoryRegionalIndicator,
+ stateLookaheadRegionalEven,
+ 0,
+ );
for (var c = 0; c < categoryCount; c++) {
if (c != categoryRegionalIndicator) {
transitionLA(state, c, stateRegionalOdd, flagBreak);
@@ -575,17 +725,26 @@
transitionLA(state, categoryLF, stateExtend, flagLookaheadBreakBoth);
transitionLA(state, categoryOther, stateOther, flagLookaheadBreakEarly);
transitionLA(
- state, categorySpacingMark, stateExtend, flagLookaheadBreakEarly);
+ state,
+ categorySpacingMark,
+ stateExtend,
+ flagLookaheadBreakEarly,
+ );
transitionLA(state, categoryOther, stateOther, flagLookaheadBreakEarly);
- transitionLA(state, categoryRegionalIndicator, stateRegionalSingle,
- flagLookaheadBreakEarly);
transitionLA(
- state,
- categoryPictographic,
- statePictographic,
- state == stateLookaheadZWJPictographic
- ? flagLookaheadBreakNone
- : flagLookaheadBreakEarly);
+ state,
+ categoryRegionalIndicator,
+ stateRegionalSingle,
+ flagLookaheadBreakEarly,
+ );
+ transitionLA(
+ state,
+ categoryPictographic,
+ statePictographic,
+ state == stateLookaheadZWJPictographic
+ ? flagLookaheadBreakNone
+ : flagLookaheadBreakEarly,
+ );
transitionLA(state, categoryPrepend, stateOther, flagLookaheadBreakEarly);
transitionLA(state, categoryL, stateL, flagLookaheadBreakEarly);
transitionLA(state, categoryLV, stateL, flagLookaheadBreakEarly);
@@ -593,19 +752,24 @@
transitionLA(state, categoryV, stateV, flagLookaheadBreakEarly);
transitionLA(state, categoryT, stateT, flagLookaheadBreakEarly);
transitionLA(
- state,
- categoryOtherIndicConsonant,
- stateInC,
- state == stateLookaheadInCL
- ? flagLookaheadBreakNone
- : flagLookaheadBreakEarly);
+ state,
+ categoryOtherIndicConsonant,
+ stateInC,
+ state == stateLookaheadInCL
+ ? flagLookaheadBreakNone
+ : flagLookaheadBreakEarly,
+ );
if (state == stateLookaheadZWJPictographic) {
transitionLA(state, categoryExtend, state, 0);
transitionLA(state, categoryZWJ, stateExtend, flagLookaheadBreakEarly);
transitionLA(state, categoryExtendIndicLinked, state, 0);
} else {
transitionLA(
- state, categoryExtend, stateExtend, flagLookaheadBreakEarly);
+ state,
+ categoryExtend,
+ stateExtend,
+ flagLookaheadBreakEarly,
+ );
transitionLA(state, categoryZWJ, state, 0);
transitionLA(state, categoryExtendIndicLinked, stateLookaheadInCL, 0);
}
@@ -629,8 +793,15 @@
}
void _writeForwardTable(Uint16List table, int automatonRowLength) {
- var automaton = _generateTable(table, automatonRowLength, stateLimit,
- stateShortName, backStateShortName, categoryShortNames, stateSoTNoBreak);
+ var automaton = _generateTable(
+ table,
+ automatonRowLength,
+ stateLimit,
+ stateShortName,
+ backStateShortName,
+ categoryShortNames,
+ stateSoTNoBreak,
+ );
stdout.write(automaton);
if (automaton != expectedAutomatonDescription) {
stderr
@@ -672,13 +843,14 @@
/// automaton based scanning.
/// The [ignoreState] is a single state that is not displayed.
String _generateTable(
- Uint16List table,
- int automatonRowLength,
- int stateLimit, // A multiple of automatonRowLength
- String Function(int) stateNames,
- String Function(int) lookaheadStateNames,
- List<String> categoryNames,
- int ignoreState) {
+ Uint16List table,
+ int automatonRowLength,
+ int stateLimit, // A multiple of automatonRowLength
+ String Function(int) stateNames,
+ String Function(int) lookaheadStateNames,
+ List<String> categoryNames,
+ int ignoreState,
+) {
assert(automatonRowLength >= categoryCount);
assert(table.length == stateLimit);
var buf = StringBuffer();
diff --git a/pkgs/characters/tool/src/data_files.dart b/pkgs/characters/tool/src/data_files.dart
index 090b6b8..5298831 100644
--- a/pkgs/characters/tool/src/data_files.dart
+++ b/pkgs/characters/tool/src/data_files.dart
@@ -9,27 +9,34 @@
// If any of these URIs stop working, find out where they have moved to.
final graphemeBreakPropertyData = DataFile(
- 'https://unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt',
- 'third_party/Unicode_Consortium/GraphemeBreakProperty.txt');
+ 'https://unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakProperty.txt',
+ 'third_party/Unicode_Consortium/GraphemeBreakProperty.txt',
+);
final emojiData = DataFile(
- 'https://unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt',
- 'third_party/Unicode_Consortium/emoji_data.txt');
+ 'https://unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt',
+ 'third_party/Unicode_Consortium/emoji_data.txt',
+);
final graphemeTestData = DataFile(
- 'https://unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt',
- 'third_party/Unicode_Consortium/GraphemeBreakTest.txt');
+ 'https://unicode.org/Public/UCD/latest/ucd/auxiliary/GraphemeBreakTest.txt',
+ 'third_party/Unicode_Consortium/GraphemeBreakTest.txt',
+);
final emojiTestData = DataFile(
- 'https://unicode.org/Public/emoji/latest/emoji-test.txt',
- 'third_party/Unicode_Consortium/emoji_test.txt');
+ 'https://unicode.org/Public/emoji/latest/emoji-test.txt',
+ 'third_party/Unicode_Consortium/emoji_test.txt',
+);
-final licenseFile = DataFile('https://www.unicode.org/license.txt',
- 'third_party/Unicode_Consortium/UNICODE_LICENSE.txt');
+final licenseFile = DataFile(
+ 'https://www.unicode.org/license.txt',
+ 'third_party/Unicode_Consortium/UNICODE_LICENSE.txt',
+);
final derivedData = DataFile(
- 'https://unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt',
- 'third_party/Unicode_Consortium/DerivedCoreProperties.txt');
+ 'https://unicode.org/Public/UCD/latest/ucd/DerivedCoreProperties.txt',
+ 'third_party/Unicode_Consortium/DerivedCoreProperties.txt',
+);
class DataFile {
/// Source URI.
@@ -53,8 +60,11 @@
/// and written to the [targetLocation] file.
Future<String> load({bool checkForUpdate = false}) async =>
(checkForUpdate ? null : _contents) ??
- (_contents = await util.fetch(sourceLocation,
- targetFile: _targetFile, forceLoad: checkForUpdate));
+ (_contents = await util.fetch(
+ sourceLocation,
+ targetFile: _targetFile,
+ forceLoad: checkForUpdate,
+ ));
/// Fetches content, compares to existing content.
///
@@ -64,8 +74,11 @@
equals ??= _eq;
var contents = await this.contents;
var tmpFile = File(util.tmpPath(targetLocation));
- var newContents =
- await util.fetch(sourceLocation, targetFile: tmpFile, forceLoad: true);
+ var newContents = await util.fetch(
+ sourceLocation,
+ targetFile: tmpFile,
+ forceLoad: true,
+ );
if (equals(contents, newContents)) {
return null;
}
diff --git a/pkgs/characters/tool/src/grapheme_category_loader.dart b/pkgs/characters/tool/src/grapheme_category_loader.dart
index 0def73a..1f436f8 100644
--- a/pkgs/characters/tool/src/grapheme_category_loader.dart
+++ b/pkgs/characters/tool/src/grapheme_category_loader.dart
@@ -15,11 +15,13 @@
/// Loads all categories by combining the categories of the
/// grapheme break property with the categories of the InCB property.
-Future<Uint8List> loadCategories(
- {bool update = false, bool verbose = false}) async {
+Future<Uint8List> loadCategories({
+ bool update = false,
+ bool verbose = false,
+}) async {
var (graphemeTable, incbTable) = await (
loadGraphemeCategories(update: update, verbose: verbose),
- loadInCBCategories(update: update, verbose: verbose)
+ loadInCBCategories(update: update, verbose: verbose),
).wait;
if (verbose) {
_logIntersection(graphemeTable, incbTable);
@@ -32,10 +34,12 @@
assert(incb == categoryExtendIndicExtend);
continue;
}
- assert(incb == categoryOtherIndicConsonant && grapheme == categoryOther ||
- (incb == categoryExtendIndicExtend ||
- incb == categoryExtendIndicLinked) &&
- grapheme == categoryExtend);
+ assert(
+ incb == categoryOtherIndicConsonant && grapheme == categoryOther ||
+ (incb == categoryExtendIndicExtend ||
+ incb == categoryExtendIndicLinked) &&
+ grapheme == categoryExtend,
+ );
graphemeTable[i] = incb;
}
}
@@ -44,8 +48,10 @@
/// Loads and parses the grapheme break categories from the grapheme break data,
/// emoji data, and adds unpaired surrogates as controls.
-Future<Uint8List> loadGraphemeCategories(
- {bool update = false, bool verbose = false}) async {
+Future<Uint8List> loadGraphemeCategories({
+ bool update = false,
+ bool verbose = false,
+}) async {
var dataFiles = await Future.wait([
graphemeBreakPropertyData.load(checkForUpdate: update),
emojiData.load(checkForUpdate: update),
@@ -53,15 +59,18 @@
// https://www.unicode.org/Public/12.0.0/ucd/auxiliary/GraphemeBreakProperty-12.0.0d16.txt
// Make sure it's included.
Future.value(
- 'D800..DFFF ; Control # Cc <control-D800>..<control-DFFF>\n'),
+ 'D800..DFFF ; Control # Cc <control-D800>..<control-DFFF>\n',
+ ),
]);
var table = _parseCategories(dataFiles, verbose: verbose);
return table;
}
/// Loads and parses the InCB categories from the derived properties data.
-Future<Uint8List> loadInCBCategories(
- {bool update = false, bool verbose = false}) async {
+Future<Uint8List> loadInCBCategories({
+ bool update = false,
+ bool verbose = false,
+}) async {
var data = await derivedData.load(checkForUpdate: update);
var table = _parseInCBCategories(data, verbose: verbose);
return table;
@@ -84,31 +93,38 @@
counts[table[i] * incbNames.length + incbOffset]++;
}
print(
- "GC/InCB ${incbNames.map((s) => s.padLeft(10)).join(" ")}");
+ "GC/InCB ${incbNames.map((s) => s.padLeft(10)).join(" ")}",
+ );
for (var i = 0; i < categoryCount; i++) {
if (i == categoryOtherIndicConsonant ||
i == categoryExtendIndicExtend ||
i == categoryExtendIndicLinked) {
- assert(counts
- .sublist(i * incbNames.length, (i + 1) * incbNames.length)
- .every((c) => c == 0));
+ assert(
+ counts
+ .sublist(i * incbNames.length, (i + 1) * incbNames.length)
+ .every((c) => c == 0),
+ );
continue;
}
- print("${categoryNames[i].padRight(20)}${[
- for (var j = 0; j < incbNames.length; j++)
- switch (counts[i * incbNames.length + j]) {
- 0 => "",
- var v => v.toString()
- }
- .padLeft(10)
- ].join(" ")}");
+ print(
+ "${categoryNames[i].padRight(20)}${[
+ for (var j = 0; j < incbNames.length; j++)
+ switch (counts[i * incbNames.length + j]) {
+ 0 => "",
+ var v => v.toString(),
+ }
+ .padLeft(10)
+ ].join(" ")}",
+ );
}
}
// -----------------------------------------------------------------------------
// Unicode table parser.
-final _tableRE = RegExp(r'^([\dA-F]{4,5})(?:..([\dA-F]{4,5}))?\s*;\s*(\w+)\s*#',
- multiLine: true);
+final _tableRE = RegExp(
+ r'^([\dA-F]{4,5})(?:..([\dA-F]{4,5}))?\s*;\s*(\w+)\s*#',
+ multiLine: true,
+);
// The relevant names that occur in the Unicode tables.
final categoryByName = {
@@ -134,7 +150,7 @@
var count = 0;
var categoryCount = <String, int>{};
var categoryMin = <String, int>{
- for (var category in categoryByName.keys) category: 0x10FFFF
+ for (var category in categoryByName.keys) category: 0x10FFFF,
};
int min(int a, int b) => a < b ? a : b;
for (var file in files) {
@@ -158,16 +174,20 @@
if (verbose) {
stderr.writeln('Loaded $count entries');
categoryCount.forEach((category, count) {
- stderr.writeln(' $category: $count, min: U+'
- "${categoryMin[category]!.toRadixString(16).padLeft(4, "0")}");
+ stderr.writeln(
+ ' $category: $count, min: U+'
+ "${categoryMin[category]!.toRadixString(16).padLeft(4, "0")}",
+ );
});
}
if (result[0xD800] != categoryControl) {
stderr.writeln('WARNING: Surrogates are not controls. Check inputs.');
}
if (categoryMin['Regional_Indicator']! < 0x10000) {
- stderr.writeln('WARNING: Regional Indicator in BMP. '
- 'Code assuming all RIs are non-BMP will fail');
+ stderr.writeln(
+ 'WARNING: Regional Indicator in BMP. '
+ 'Code assuming all RIs are non-BMP will fail',
+ );
}
return result;
}
@@ -193,16 +213,17 @@
// Luckily it is precomputed in a file of its own.
final _derivedPropertyTableRE = RegExp(
- r'^([\dA-F]{4,5})(?:..([\dA-F]{4,5}))?\s*;\s*InCB\s*;\s*(\w+)\s*#'
- r'|'
- r'^# Total code points: (\d+)',
- multiLine: true);
+ r'^([\dA-F]{4,5})(?:..([\dA-F]{4,5}))?\s*;\s*InCB\s*;\s*(\w+)\s*#'
+ r'|'
+ r'^# Total code points: (\d+)',
+ multiLine: true,
+);
Uint8List _parseInCBCategories(String file, {required bool verbose}) {
const categoryByName = {
'Consonant': categoryOtherIndicConsonant,
'Extend': categoryExtendIndicExtend,
- 'Linker': categoryExtendIndicLinked
+ 'Linker': categoryExtendIndicLinked,
};
var result = Uint8List(0x110000);
var lines = 0;
@@ -215,7 +236,9 @@
if (currentInCBCategory.isNotEmpty) {
if (totalCounts[currentInCBCategory] != 0) {
throw FormatException(
- 'More than one total count per category', match[0]!);
+ 'More than one total count per category',
+ match[0]!,
+ );
}
totalCounts[currentInCBCategory] = int.parse(totalCountText);
currentInCBCategory = '';
@@ -249,15 +272,19 @@
}
for (var name in categoryByName.keys) {
if (counts[name] != totalCounts[name]) {
- stderr.writeln('${categoryByName[name]}: '
- 'Parsed: ${counts[name]}, expected: ${totalCounts[name]}');
+ stderr.writeln(
+ '${categoryByName[name]}: '
+ 'Parsed: ${counts[name]}, expected: ${totalCounts[name]}',
+ );
}
}
if (verbose) {
stderr.writeln('InCB categories: Loaded $count entries from $lines lines');
for (var name in categoryByName.keys) {
- stderr.writeln(' ${name.padRight(9)}: '
- '${counts[name].toString().padLeft(6)}');
+ stderr.writeln(
+ ' ${name.padRight(9)}: '
+ '${counts[name].toString().padLeft(6)}',
+ );
}
}
return result;
@@ -274,8 +301,10 @@
static const int _entryMask = _entrySize - 1;
static const int _entryShift = 8;
static const int _entryCount = _unicodeCodePoints >> _entryShift;
- final List<_TableEntry> _entries =
- List.filled(_entryCount, const _ValueEntry(0));
+ final List<_TableEntry> _entries = List.filled(
+ _entryCount,
+ const _ValueEntry(0),
+ );
int operator [](int index) =>
_entries[index >> _entryShift][index & _entryMask];
@@ -296,14 +325,22 @@
fullEntry = _ValueEntry(value); // TODO: Cache these per value.
}
while (startEntry < endEntry) {
- _entries[startEntry] = _entries[startEntry]
- .fillRange(startOffset, _entrySize, value, fullEntry);
+ _entries[startEntry] = _entries[startEntry].fillRange(
+ startOffset,
+ _entrySize,
+ value,
+ fullEntry,
+ );
startOffset = 0;
}
var endOffset = end & _entryMask;
if (endOffset > 0) {
- _entries[endEntry] = _entries[endEntry]
- .fillRange(startOffset, endOffset, value, fullEntry);
+ _entries[endEntry] = _entries[endEntry].fillRange(
+ startOffset,
+ endOffset,
+ value,
+ fullEntry,
+ );
}
}
}
@@ -338,7 +375,11 @@
@override
_TableEntry _fillRange(
- int start, int end, int value, _ValueEntry? fullEntry) {
+ int start,
+ int end,
+ int value,
+ _ValueEntry? fullEntry,
+ ) {
if (value == this.value) return fullEntry ?? this;
return _toListEntry()._fillRange(start, end, value, fullEntry);
}
@@ -365,7 +406,11 @@
@override
_TableEntry _fillRange(
- int start, int end, int value, _ValueEntry? fullEntry) {
+ int start,
+ int end,
+ int value,
+ _ValueEntry? fullEntry,
+ ) {
values.fillRange(start, end, value);
return this;
}
diff --git a/pkgs/characters/tool/src/shared.dart b/pkgs/characters/tool/src/shared.dart
index 69ccb97..136cb8c 100644
--- a/pkgs/characters/tool/src/shared.dart
+++ b/pkgs/characters/tool/src/shared.dart
@@ -17,8 +17,11 @@
///
/// If [targetFile] is omitted, a file in the system temporary directory
/// is used instead.
-Future<String> fetch(String location,
- {File? targetFile, bool forceLoad = false}) async {
+Future<String> fetch(
+ String location, {
+ File? targetFile,
+ bool forceLoad = false,
+}) async {
if (targetFile == null) {
var safeLocation = safePath(location);
targetFile = File(path(Directory.systemTemp.path, safeLocation));
@@ -69,7 +72,8 @@
if (await licenseFile.checkChange() case var changedLicensePath?) {
if (!acceptLicenseChange) {
stderr.writeln(
- licenseChangeWarning(licenseFile.targetLocation, changedLicensePath));
+ licenseChangeWarning(licenseFile.targetLocation, changedLicensePath),
+ );
return false;
}
stderr.writeln('LICENSE CHANGE ACCEPTED!');
@@ -113,8 +117,10 @@
}
output
..writeln('// Licensed under the Unicode Inc. License Agreement')
- ..writeln('// (${licenseFile.sourceLocation}, '
- '../../third_party/${licenseFile.targetLocation})');
+ ..writeln(
+ '// (${licenseFile.sourceLocation}, '
+ '../../third_party/${licenseFile.targetLocation})',
+ );
}
/// Temporary directory. Created once and for all.
@@ -177,7 +183,8 @@
var parent = dir.parent;
if (dir.path == parent.path) {
throw UnsupportedError(
- 'Cannot find package root directory. Run tools from inside package!');
+ 'Cannot find package root directory. Run tools from inside package!',
+ );
}
}
}
diff --git a/pkgs/characters/tool/src/string_literal_writer.dart b/pkgs/characters/tool/src/string_literal_writer.dart
index 52a62d1..9259b4e 100644
--- a/pkgs/characters/tool/src/string_literal_writer.dart
+++ b/pkgs/characters/tool/src/string_literal_writer.dart
@@ -16,9 +16,12 @@
static final Map<int, String> _escapeCache = {};
- StringLiteralWriter(this.buffer,
- {int padding = 0, int lineLength = 80, bool Function(int)? escape})
- : _padding = ' ' * padding,
+ StringLiteralWriter(
+ this.buffer, {
+ int padding = 0,
+ int lineLength = 80,
+ bool Function(int)? escape,
+ }) : _padding = ' ' * padding,
_lineLength = lineLength,
_escape = escape ?? _defaultEscape;
diff --git a/pkgs/characters/tool/src/table_builder.dart b/pkgs/characters/tool/src/table_builder.dart
index d407f4a..4a49d45 100644
--- a/pkgs/characters/tool/src/table_builder.dart
+++ b/pkgs/characters/tool/src/table_builder.dart
@@ -22,8 +22,10 @@
var entries = table.entries.toList();
entries.sort((a, b) => b.length - a.length);
var uniqueChunks = <Uint8List>[];
- var duplicateDetector =
- HashMap<Uint8List, TableEntry>(equals: _equals, hashCode: _hash);
+ var duplicateDetector = HashMap<Uint8List, TableEntry>(
+ equals: _equals,
+ hashCode: _hash,
+ );
for (var entry in entries) {
var chunk = data.sublist(entry.start, entry.end);
var existingEntry = duplicateDetector[chunk];
diff --git a/pkgs/collection/CHANGELOG.md b/pkgs/collection/CHANGELOG.md
index 5164fca..743fddf 100644
--- a/pkgs/collection/CHANGELOG.md
+++ b/pkgs/collection/CHANGELOG.md
@@ -1,4 +1,3 @@
-
## 1.20.0-wip
- Add `IterableMapEntryExtension` for working on `Map` as a list of pairs, using
@@ -9,6 +8,7 @@
iterator to avoid extra lookups.
- Add `PriorityQueue.of` constructor and optimize adding many elements.
- Address diagnostics from `strict_top_level_inference`.
+- Run `dart format` with the new style.
## 1.19.1
diff --git a/pkgs/collection/benchmark/deep_collection_equality.dart b/pkgs/collection/benchmark/deep_collection_equality.dart
index 182cf86..df44955 100644
--- a/pkgs/collection/benchmark/deep_collection_equality.dart
+++ b/pkgs/collection/benchmark/deep_collection_equality.dart
@@ -49,17 +49,13 @@
final mapA = {
for (var i = 0; i < 100; i++)
{
- [
- for (var j = i; j < i + 10; j++) j,
- ]: i.isEven ? i : '$i',
- }
+ [for (var j = i; j < i + 10; j++) j]: i.isEven ? i : '$i',
+ },
};
final mapB = {
for (var i = 0; i < 100; i++)
{
- [
- for (var j = i; j < i + 10; j++) j,
- ]: i.isEven ? i : '$i',
- }
+ [for (var j = i; j < i + 10; j++) j]: i.isEven ? i : '$i',
+ },
};
diff --git a/pkgs/collection/lib/src/algorithms.dart b/pkgs/collection/lib/src/algorithms.dart
index bb5843c..88d1c4f 100644
--- a/pkgs/collection/lib/src/algorithms.dart
+++ b/pkgs/collection/lib/src/algorithms.dart
@@ -18,8 +18,11 @@
/// the objects. In this case, the objects must be [Comparable].
///
/// Returns -1 if [value] is not in the list.
-int binarySearch<E>(List<E> sortedList, E value,
- {int Function(E, E)? compare}) {
+int binarySearch<E>(
+ List<E> sortedList,
+ E value, {
+ int Function(E, E)? compare,
+}) {
compare ??= defaultCompare;
return binarySearchBy<E, E>(sortedList, identity, compare, value);
}
@@ -33,9 +36,14 @@
///
/// If [start] and [end] are supplied, only that range is searched,
/// and only that range need to be sorted.
-int binarySearchBy<E, K>(List<E> sortedList, K Function(E element) keyOf,
- int Function(K, K) compare, E value,
- [int start = 0, int? end]) {
+int binarySearchBy<E, K>(
+ List<E> sortedList,
+ K Function(E element) keyOf,
+ int Function(K, K) compare,
+ E value, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, sortedList.length);
var min = start;
var max = end;
@@ -86,9 +94,14 @@
///
/// If [start] and [end] are supplied, only that range is searched,
/// and only that range need to be sorted.
-int lowerBoundBy<E, K>(List<E> sortedList, K Function(E element) keyOf,
- int Function(K, K) compare, E value,
- [int start = 0, int? end]) {
+int lowerBoundBy<E, K>(
+ List<E> sortedList,
+ K Function(E element) keyOf,
+ int Function(K, K) compare,
+ E value, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, sortedList.length);
var min = start;
var max = end;
@@ -157,8 +170,12 @@
///
/// This insertion sort is stable: Equal elements end up in the same order
/// as they started in.
-void insertionSort<E>(List<E> elements,
- {int Function(E, E)? compare, int start = 0, int? end}) {
+void insertionSort<E>(
+ List<E> elements, {
+ int Function(E, E)? compare,
+ int start = 0,
+ int? end,
+}) {
// If the same method could have both positional and named optional
// parameters, this should be (list, [start, end], {compare}).
compare ??= defaultCompare;
@@ -186,9 +203,13 @@
///
/// Performs insertion sort on the [elements] range from [start] to [end].
/// Ordering is the [compare] of the [keyOf] of the elements.
-void insertionSortBy<E, K>(List<E> elements, K Function(E element) keyOf,
- int Function(K a, K b) compare,
- [int start = 0, int? end]) {
+void insertionSortBy<E, K>(
+ List<E> elements,
+ K Function(E element) keyOf,
+ int Function(K a, K b) compare, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, elements.length);
_movingInsertionSort(elements, keyOf, compare, start, end, elements, start);
}
@@ -211,8 +232,12 @@
///
/// This merge sort is stable: Equal elements end up in the same order
/// as they started in.
-void mergeSort<E>(List<E> elements,
- {int start = 0, int? end, int Function(E, E)? compare}) {
+void mergeSort<E>(
+ List<E> elements, {
+ int start = 0,
+ int? end,
+ int Function(E, E)? compare,
+}) {
end = RangeError.checkValidRange(start, end, elements.length);
compare ??= defaultCompare;
@@ -236,9 +261,26 @@
_mergeSort(elements, identity<E>, compare, middle, end, scratchSpace, 0);
var firstTarget = end - firstLength;
_mergeSort(
- elements, identity<E>, compare, start, middle, elements, firstTarget);
- _merge(identity<E>, compare, elements, firstTarget, end, scratchSpace, 0,
- secondLength, elements, start);
+ elements,
+ identity<E>,
+ compare,
+ start,
+ middle,
+ elements,
+ firstTarget,
+ );
+ _merge(
+ identity<E>,
+ compare,
+ elements,
+ firstTarget,
+ end,
+ scratchSpace,
+ 0,
+ secondLength,
+ elements,
+ start,
+ );
}
/// Sort [elements] using a merge-sort algorithm.
@@ -248,9 +290,13 @@
/// If [start] and [end] are provided, only that range is sorted.
///
/// Uses insertion sort for smaller sublists.
-void mergeSortBy<E, K>(List<E> elements, K Function(E element) keyOf,
- int Function(K a, K b) compare,
- [int start = 0, int? end]) {
+void mergeSortBy<E, K>(
+ List<E> elements,
+ K Function(E element) keyOf,
+ int Function(K a, K b) compare, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, elements.length);
var length = end - start;
if (length < 2) return;
@@ -272,8 +318,18 @@
_mergeSort(elements, keyOf, compare, middle, end, scratchSpace, 0);
var firstTarget = end - firstLength;
_mergeSort(elements, keyOf, compare, start, middle, elements, firstTarget);
- _merge(keyOf, compare, elements, firstTarget, end, scratchSpace, 0,
- secondLength, elements, start);
+ _merge(
+ keyOf,
+ compare,
+ elements,
+ firstTarget,
+ end,
+ scratchSpace,
+ 0,
+ secondLength,
+ elements,
+ start,
+ );
}
/// Performs an insertion sort into a potentially different list than the
@@ -281,13 +337,14 @@
///
/// It will work in-place as well.
void _movingInsertionSort<E, K>(
- List<E> list,
- K Function(E element) keyOf,
- int Function(K, K) compare,
- int start,
- int end,
- List<E> target,
- int targetOffset) {
+ List<E> list,
+ K Function(E element) keyOf,
+ int Function(K, K) compare,
+ int start,
+ int end,
+ List<E> target,
+ int targetOffset,
+) {
var length = end - start;
if (length == 0) return;
target[targetOffset] = list[start];
@@ -317,17 +374,25 @@
/// Allows target to be the same list as [elements], as long as it's not
/// overlapping the `start..end` range.
void _mergeSort<E, K>(
- List<E> elements,
- K Function(E element) keyOf,
- int Function(K, K) compare,
- int start,
- int end,
- List<E> target,
- int targetOffset) {
+ List<E> elements,
+ K Function(E element) keyOf,
+ int Function(K, K) compare,
+ int start,
+ int end,
+ List<E> target,
+ int targetOffset,
+) {
var length = end - start;
if (length < _mergeSortLimit) {
_movingInsertionSort<E, K>(
- elements, keyOf, compare, start, end, target, targetOffset);
+ elements,
+ keyOf,
+ compare,
+ start,
+ end,
+ target,
+ targetOffset,
+ );
return;
}
var middle = start + (length >> 1);
@@ -340,8 +405,18 @@
// Sort the first half into the end of the source area.
_mergeSort(elements, keyOf, compare, start, middle, elements, middle);
// Merge the two parts into the target area.
- _merge(keyOf, compare, elements, middle, middle + firstLength, target,
- targetMiddle, targetMiddle + secondLength, target, targetOffset);
+ _merge(
+ keyOf,
+ compare,
+ elements,
+ middle,
+ middle + firstLength,
+ target,
+ targetMiddle,
+ targetMiddle + secondLength,
+ target,
+ targetOffset,
+ );
}
/// Merges two lists into a target list.
@@ -353,16 +428,17 @@
/// This allows the merge to be stable if the first list contains elements
/// that started out earlier than the ones in [secondList]
void _merge<E, K>(
- K Function(E element) keyOf,
- int Function(K, K) compare,
- List<E> firstList,
- int firstStart,
- int firstEnd,
- List<E> secondList,
- int secondStart,
- int secondEnd,
- List<E> target,
- int targetOffset) {
+ K Function(E element) keyOf,
+ int Function(K, K) compare,
+ List<E> firstList,
+ int firstStart,
+ int firstEnd,
+ List<E> secondList,
+ int secondStart,
+ int secondEnd,
+ List<E> target,
+ int targetOffset,
+) {
// No empty lists reaches here.
assert(firstStart < firstEnd);
assert(secondStart < secondEnd);
@@ -387,15 +463,23 @@
}
// Second list empties first. Flushing first list here.
target[targetOffset++] = firstElement;
- target.setRange(targetOffset, targetOffset + (firstEnd - cursor1),
- firstList, cursor1);
+ target.setRange(
+ targetOffset,
+ targetOffset + (firstEnd - cursor1),
+ firstList,
+ cursor1,
+ );
return;
}
}
// First list empties first. Reached by break above.
target[targetOffset++] = secondElement;
target.setRange(
- targetOffset, targetOffset + (secondEnd - cursor2), secondList, cursor2);
+ targetOffset,
+ targetOffset + (secondEnd - cursor2),
+ secondList,
+ cursor2,
+ );
}
/// Sort [elements] using a quick-sort algorithm.
@@ -404,8 +488,12 @@
/// If [start] and [end] are provided, only that range is sorted.
///
/// Uses insertion sort for smaller sublists.
-void quickSort<E>(List<E> elements, int Function(E a, E b) compare,
- [int start = 0, int? end]) {
+void quickSort<E>(
+ List<E> elements,
+ int Function(E a, E b) compare, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, elements.length);
_quickSort<E, E>(elements, identity, compare, Random(), start, end);
}
@@ -418,14 +506,24 @@
///
/// Uses insertion sort for smaller sublists.
void quickSortBy<E, K>(
- List<E> list, K Function(E element) keyOf, int Function(K a, K b) compare,
- [int start = 0, int? end]) {
+ List<E> list,
+ K Function(E element) keyOf,
+ int Function(K a, K b) compare, [
+ int start = 0,
+ int? end,
+]) {
end = RangeError.checkValidRange(start, end, list.length);
_quickSort(list, keyOf, compare, Random(), start, end);
}
-void _quickSort<E, K>(List<E> list, K Function(E element) keyOf,
- int Function(K a, K b) compare, Random random, int start, int end) {
+void _quickSort<E, K>(
+ List<E> list,
+ K Function(E element) keyOf,
+ int Function(K a, K b) compare,
+ Random random,
+ int start,
+ int end,
+) {
const minQuickSortLength = 24;
var length = end - start;
while (length >= minQuickSortLength) {
diff --git a/pkgs/collection/lib/src/boollist.dart b/pkgs/collection/lib/src/boollist.dart
index 6b973e0..dc6bef9 100644
--- a/pkgs/collection/lib/src/boollist.dart
+++ b/pkgs/collection/lib/src/boollist.dart
@@ -194,10 +194,7 @@
static const int _growthFactor = 2;
_GrowableBoolList._withCapacity(int length, int capacity)
- : super._(
- Uint32List(BoolList._lengthInWords(capacity)),
- length,
- );
+ : super._(Uint32List(BoolList._lengthInWords(capacity)), length);
_GrowableBoolList(int length)
: super._(
@@ -217,9 +214,8 @@
void _expand(int length) {
if (length > _data.length * BoolList._bitsPerEntry) {
- _data = Uint32List(
- BoolList._lengthInWords(length * _growthFactor),
- )..setRange(0, _data.length, _data);
+ _data = Uint32List(BoolList._lengthInWords(length * _growthFactor))
+ ..setRange(0, _data.length, _data);
}
_length = length;
}
@@ -241,16 +237,10 @@
final class _NonGrowableBoolList extends BoolList
with NonGrowableListMixin<bool> {
_NonGrowableBoolList._withCapacity(int length, int capacity)
- : super._(
- Uint32List(BoolList._lengthInWords(capacity)),
- length,
- );
+ : super._(Uint32List(BoolList._lengthInWords(capacity)), length);
_NonGrowableBoolList(int length)
- : super._(
- Uint32List(BoolList._lengthInWords(length)),
- length,
- );
+ : super._(Uint32List(BoolList._lengthInWords(length)), length);
}
class _BoolListIterator implements Iterator<bool> {
diff --git a/pkgs/collection/lib/src/canonicalized_map.dart b/pkgs/collection/lib/src/canonicalized_map.dart
index 3dc6e37..753ebe6 100644
--- a/pkgs/collection/lib/src/canonicalized_map.dart
+++ b/pkgs/collection/lib/src/canonicalized_map.dart
@@ -25,9 +25,10 @@
/// The [isValidKey] function is called before calling [canonicalize] for
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
- CanonicalizedMap(C Function(K key) canonicalize,
- {bool Function(K key)? isValidKey})
- : _canonicalize = canonicalize,
+ CanonicalizedMap(
+ C Function(K key) canonicalize, {
+ bool Function(K key)? isValidKey,
+ }) : _canonicalize = canonicalize,
_isValidKeyFn = isValidKey;
/// Creates a canonicalized map that is initialized with the key/value pairs
@@ -39,9 +40,11 @@
/// The [isValidKey] function is called before calling [canonicalize] for
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
- CanonicalizedMap.from(Map<K, V> other, C Function(K key) canonicalize,
- {bool Function(K key)? isValidKey})
- : _canonicalize = canonicalize,
+ CanonicalizedMap.from(
+ Map<K, V> other,
+ C Function(K key) canonicalize, {
+ bool Function(K key)? isValidKey,
+ }) : _canonicalize = canonicalize,
_isValidKeyFn = isValidKey {
addAll(other);
}
@@ -56,15 +59,19 @@
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
CanonicalizedMap.fromEntries(
- Iterable<MapEntry<K, V>> entries, C Function(K key) canonicalize,
- {bool Function(K key)? isValidKey})
- : _canonicalize = canonicalize,
+ Iterable<MapEntry<K, V>> entries,
+ C Function(K key) canonicalize, {
+ bool Function(K key)? isValidKey,
+ }) : _canonicalize = canonicalize,
_isValidKeyFn = isValidKey {
addEntries(entries);
}
CanonicalizedMap._(
- this._canonicalize, this._isValidKeyFn, Map<C, MapEntry<K, V>> base) {
+ this._canonicalize,
+ this._isValidKeyFn,
+ Map<C, MapEntry<K, V>> base,
+ ) {
_base.addAll(base);
}
@@ -92,8 +99,11 @@
}
@override
- void addEntries(Iterable<MapEntry<K, V>> entries) => _base.addEntries(entries
- .map((e) => MapEntry(_canonicalize(e.key), MapEntry(e.key, e.value))));
+ void addEntries(Iterable<MapEntry<K, V>> entries) => _base.addEntries(
+ entries.map(
+ (e) => MapEntry(_canonicalize(e.key), MapEntry(e.key, e.value)),
+ ),
+ );
@override
Map<K2, V2> cast<K2, V2>() => _base.cast<K2, V2>();
@@ -161,14 +171,16 @@
@override
V update(K key, V Function(V) update, {V Function()? ifAbsent}) =>
- _base.update(_canonicalize(key), (pair) {
- var value = pair.value;
- var newValue = update(value);
- if (identical(newValue, value)) return pair;
- return MapEntry(key, newValue);
- },
- ifAbsent:
- ifAbsent == null ? null : () => MapEntry(key, ifAbsent())).value;
+ _base.update(
+ _canonicalize(key),
+ (pair) {
+ var value = pair.value;
+ var newValue = update(value);
+ if (identical(newValue, value)) return pair;
+ return MapEntry(key, newValue);
+ },
+ ifAbsent: ifAbsent == null ? null : () => MapEntry(key, ifAbsent()),
+ ).value;
@override
void updateAll(V Function(K key, V value) update) =>
@@ -196,5 +208,6 @@
/// Creates a `Map<C,V>` (with the canonicalized keys).
/// See [toMap].
Map<C, V> toMapOfCanonicalKeys() => Map<C, V>.fromEntries(
- _base.entries.map((e) => MapEntry<C, V>(e.key, e.value.value)));
+ _base.entries.map((e) => MapEntry<C, V>(e.key, e.value.value)),
+ );
}
diff --git a/pkgs/collection/lib/src/combined_wrappers/combined_map.dart b/pkgs/collection/lib/src/combined_wrappers/combined_map.dart
index 18db6e7..baee82e 100644
--- a/pkgs/collection/lib/src/combined_wrappers/combined_map.dart
+++ b/pkgs/collection/lib/src/combined_wrappers/combined_map.dart
@@ -56,7 +56,8 @@
/// the future.
@override
Iterable<K> get keys => _DeduplicatingIterableView(
- CombinedIterableView(_maps.map((m) => m.keys)));
+ CombinedIterableView(_maps.map((m) => m.keys)),
+ );
}
/// A view of an iterable that skips any duplicate entries.
diff --git a/pkgs/collection/lib/src/equality.dart b/pkgs/collection/lib/src/equality.dart
index 0e1df23..88d1987 100644
--- a/pkgs/collection/lib/src/equality.dart
+++ b/pkgs/collection/lib/src/equality.dart
@@ -51,9 +51,10 @@
final Equality<F> _inner;
- EqualityBy(F Function(E) comparisonKey,
- [Equality<F> inner = const DefaultEquality<Never>()])
- : _comparisonKey = comparisonKey,
+ EqualityBy(
+ F Function(E) comparisonKey, [
+ Equality<F> inner = const DefaultEquality<Never>(),
+ ]) : _comparisonKey = comparisonKey,
_inner = inner;
@override
@@ -111,9 +112,9 @@
/// The [hash] of `null` is `null.hashCode`.
class IterableEquality<E> implements Equality<Iterable<E>> {
final Equality<E?> _elementEquality;
- const IterableEquality(
- [Equality<E> elementEquality = const DefaultEquality<Never>()])
- : _elementEquality = elementEquality;
+ const IterableEquality([
+ Equality<E> elementEquality = const DefaultEquality<Never>(),
+ ]) : _elementEquality = elementEquality;
@override
bool equals(Iterable<E>? elements1, Iterable<E>? elements2) {
@@ -163,9 +164,9 @@
/// The [hash] of `null` is `null.hashCode`.
class ListEquality<E> implements Equality<List<E>> {
final Equality<E> _elementEquality;
- const ListEquality(
- [Equality<E> elementEquality = const DefaultEquality<Never>()])
- : _elementEquality = elementEquality;
+ const ListEquality([
+ Equality<E> elementEquality = const DefaultEquality<Never>(),
+ ]) : _elementEquality = elementEquality;
@override
bool equals(List<E>? list1, List<E>? list2) {
@@ -213,9 +214,10 @@
if (identical(elements1, elements2)) return true;
if (elements1 == null || elements2 == null) return false;
var counts = HashMap<E, int>(
- equals: _elementEquality.equals,
- hashCode: _elementEquality.hash,
- isValidKey: _elementEquality.isValidKey);
+ equals: _elementEquality.equals,
+ hashCode: _elementEquality.hash,
+ isValidKey: _elementEquality.isValidKey,
+ );
var length = 0;
for (var e in elements1) {
var count = counts[e] ?? 0;
@@ -252,8 +254,9 @@
/// and the elements of one set can be paired with the elements
/// of the other iterable, so that each pair are equal.
class UnorderedIterableEquality<E> extends _UnorderedEquality<E, Iterable<E>> {
- const UnorderedIterableEquality(
- [super.elementEquality = const DefaultEquality<Never>()]);
+ const UnorderedIterableEquality([
+ super.elementEquality = const DefaultEquality<Never>(),
+ ]);
@override
bool isValidKey(Object? o) => o is Iterable<E>;
@@ -312,10 +315,10 @@
class MapEquality<K, V> implements Equality<Map<K, V>> {
final Equality<K> _keyEquality;
final Equality<V> _valueEquality;
- const MapEquality(
- {Equality<K> keys = const DefaultEquality<Never>(),
- Equality<V> values = const DefaultEquality<Never>()})
- : _keyEquality = keys,
+ const MapEquality({
+ Equality<K> keys = const DefaultEquality<Never>(),
+ Equality<V> values = const DefaultEquality<Never>(),
+ }) : _keyEquality = keys,
_valueEquality = values;
@override
@@ -428,9 +431,9 @@
/// Creates a deep equality on collections where the order of lists and
/// iterables are not considered important. That is, lists and iterables are
/// treated as unordered iterables.
- const DeepCollectionEquality.unordered(
- [Equality base = const DefaultEquality<Never>()])
- : _base = base,
+ const DeepCollectionEquality.unordered([
+ Equality base = const DefaultEquality<Never>(),
+ ]) : _base = base,
_unordered = true;
@override
diff --git a/pkgs/collection/lib/src/equality_map.dart b/pkgs/collection/lib/src/equality_map.dart
index 542977f..bf12143 100644
--- a/pkgs/collection/lib/src/equality_map.dart
+++ b/pkgs/collection/lib/src/equality_map.dart
@@ -11,10 +11,13 @@
class EqualityMap<K, V> extends DelegatingMap<K, V> {
/// Creates a map with equality based on [equality].
EqualityMap(Equality<K> equality)
- : super(LinkedHashMap(
+ : super(
+ LinkedHashMap(
equals: equality.equals,
hashCode: equality.hash,
- isValidKey: equality.isValidKey));
+ isValidKey: equality.isValidKey,
+ ),
+ );
/// Creates a map with equality based on [equality] that contains all
/// key-value pairs of [other].
@@ -22,10 +25,13 @@
/// If [other] has multiple keys that are equivalent according to [equality],
/// the last one reached during iteration takes precedence.
EqualityMap.from(Equality<K> equality, Map<K, V> other)
- : super(LinkedHashMap(
+ : super(
+ LinkedHashMap(
equals: equality.equals,
hashCode: equality.hash,
- isValidKey: equality.isValidKey)) {
+ isValidKey: equality.isValidKey,
+ ),
+ ) {
addAll(other);
}
}
diff --git a/pkgs/collection/lib/src/equality_set.dart b/pkgs/collection/lib/src/equality_set.dart
index 8edbba5..a716e00 100644
--- a/pkgs/collection/lib/src/equality_set.dart
+++ b/pkgs/collection/lib/src/equality_set.dart
@@ -11,10 +11,13 @@
class EqualitySet<E> extends DelegatingSet<E> {
/// Creates a set with equality based on [equality].
EqualitySet(Equality<E> equality)
- : super(LinkedHashSet(
+ : super(
+ LinkedHashSet(
equals: equality.equals,
hashCode: equality.hash,
- isValidKey: equality.isValidKey));
+ isValidKey: equality.isValidKey,
+ ),
+ );
/// Creates a set with equality based on [equality] that contains all
/// elements in [other].
@@ -22,10 +25,13 @@
/// If [other] has multiple values that are equivalent according to
/// [equality], the first one reached during iteration takes precedence.
EqualitySet.from(Equality<E> equality, Iterable<E> other)
- : super(LinkedHashSet(
+ : super(
+ LinkedHashSet(
equals: equality.equals,
hashCode: equality.hash,
- isValidKey: equality.isValidKey)) {
+ isValidKey: equality.isValidKey,
+ ),
+ ) {
addAll(other);
}
}
diff --git a/pkgs/collection/lib/src/functions.dart b/pkgs/collection/lib/src/functions.dart
index db86574..24c7713 100644
--- a/pkgs/collection/lib/src/functions.dart
+++ b/pkgs/collection/lib/src/functions.dart
@@ -12,8 +12,11 @@
/// The return values of [key] are used as the keys and the return values of
/// [value] are used as the values for the new map.
@Deprecated('Use Map.map or a for loop in a Map literal.')
-Map<K2, V2> mapMap<K1, V1, K2, V2>(Map<K1, V1> map,
- {K2 Function(K1, V1)? key, V2 Function(K1, V1)? value}) {
+Map<K2, V2> mapMap<K1, V1, K2, V2>(
+ Map<K1, V1> map, {
+ K2 Function(K1, V1)? key,
+ V2 Function(K1, V1)? value,
+}) {
var keyFn = key ?? (mapKey, _) => mapKey as K2;
var valueFn = value ?? (_, mapValue) => mapValue as V2;
@@ -29,8 +32,11 @@
/// If there are keys that occur in both maps, the [value] function is used to
/// select the value that goes into the resulting map based on the two original
/// values. If [value] is omitted, the value from [map2] is used.
-Map<K, V> mergeMaps<K, V>(Map<K, V> map1, Map<K, V> map2,
- {V Function(V, V)? value}) {
+Map<K, V> mergeMaps<K, V>(
+ Map<K, V> map1,
+ Map<K, V> map2, {
+ V Function(V, V)? value,
+}) {
var result = Map<K, V>.of(map1);
if (value == null) return result..addAll(map2);
@@ -45,8 +51,9 @@
///
/// Returns a map from keys computed by [key] to the last value for which [key]
/// returns that key.
-Map<T, S> lastBy<S, T>(Iterable<S> values, T Function(S) key) =>
- {for (var element in values) key(element): element};
+Map<T, S> lastBy<S, T>(Iterable<S> values, T Function(S) key) => {
+ for (var element in values) key(element): element,
+ };
/// Groups the elements in [values] by the value returned by [key].
///
@@ -69,8 +76,11 @@
/// are compared using their [Comparable.compareTo].
///
/// Returns `null` if [values] is empty.
-S? minBy<S, T>(Iterable<S> values, T Function(S) orderBy,
- {int Function(T, T)? compare}) {
+S? minBy<S, T>(
+ Iterable<S> values,
+ T Function(S) orderBy, {
+ int Function(T, T)? compare,
+}) {
compare ??= defaultCompare;
S? minValue;
@@ -93,8 +103,11 @@
/// are compared using their [Comparable.compareTo].
///
/// Returns `null` if [values] is empty.
-S? maxBy<S, T>(Iterable<S> values, T Function(S) orderBy,
- {int Function(T, T)? compare}) {
+S? maxBy<S, T>(
+ Iterable<S> values,
+ T Function(S) orderBy, {
+ int Function(T, T)? compare,
+}) {
compare ??= defaultCompare;
S? maxValue;
diff --git a/pkgs/collection/lib/src/iterable_extensions.dart b/pkgs/collection/lib/src/iterable_extensions.dart
index 10f4676..d9516e6 100644
--- a/pkgs/collection/lib/src/iterable_extensions.dart
+++ b/pkgs/collection/lib/src/iterable_extensions.dart
@@ -83,7 +83,9 @@
/// The elements are ordered by the [compare] [Comparator] of the
/// property [keyOf] of the element.
List<T> sortedByCompare<K>(
- K Function(T element) keyOf, Comparator<K> compare) {
+ K Function(T element) keyOf,
+ Comparator<K> compare,
+ ) {
var elements = [...this];
mergeSortBy<T, K>(elements, keyOf, compare);
return elements;
@@ -131,7 +133,9 @@
/// then checks whether the results are in non-decreasing order
/// using the [compare] [Comparator]..
bool isSortedByCompare<K>(
- K Function(T element) keyOf, Comparator<K> compare) {
+ K Function(T element) keyOf,
+ Comparator<K> compare,
+ ) {
var iterator = this.iterator;
if (!iterator.moveNext()) return true;
var previousKey = keyOf(iterator.current);
@@ -202,7 +206,8 @@
/// Expands each element and index to a number of elements in a new iterable.
Iterable<R> expandIndexed<R>(
- Iterable<R> Function(int index, T element) expand) sync* {
+ Iterable<R> Function(int index, T element) expand,
+ ) sync* {
var index = 0;
for (var element in this) {
yield* expand(index++, element);
@@ -241,7 +246,9 @@
/// Returns the result of the last call to [combine],
/// or [initialValue] if there are no elements.
R foldIndexed<R>(
- R initialValue, R Function(int index, R previous, T element) combine) {
+ R initialValue,
+ R Function(int index, R previous, T element) combine,
+ ) {
var result = initialValue;
var index = 0;
for (var element in this) {
@@ -395,7 +402,9 @@
/// (Set<T>? previous, T element) => (previous ?? <T>{})..add(element));
/// ````
Map<K, G> groupFoldBy<K, G>(
- K Function(T element) keyOf, G Function(G? previous, T element) combine) {
+ K Function(T element) keyOf,
+ G Function(G? previous, T element) combine,
+ ) {
var result = <K, G>{};
for (var element in this) {
var key = keyOf(element);
@@ -487,7 +496,8 @@
/// print(parts); // ([1], [0, 2], [1, 5, 7], [6, 8, 9])
/// ```
Iterable<List<T>> splitBeforeIndexed(
- bool Function(int index, T element) test) sync* {
+ bool Function(int index, T element) test,
+ ) sync* {
var iterator = this.iterator;
if (!iterator.moveNext()) {
return;
@@ -522,7 +532,8 @@
/// print(parts); // ([1, 0], [2, 1], [5, 7, 6], [8, 9])
/// ```
Iterable<List<T>> splitAfterIndexed(
- bool Function(int index, T element) test) sync* {
+ bool Function(int index, T element) test,
+ ) sync* {
var index = 0;
List<T>? chunk;
for (var element in this) {
@@ -550,7 +561,8 @@
/// print(parts); // ([1], [0, 2], [1, 5, 7], [6, 8, 9])
/// ```
Iterable<List<T>> splitBetweenIndexed(
- bool Function(int index, T first, T second) test) sync* {
+ bool Function(int index, T first, T second) test,
+ ) sync* {
var iterator = this.iterator;
if (!iterator.moveNext()) return;
var previous = iterator.current;
@@ -899,9 +911,7 @@
/// For each one, which is itself an iterable,
/// all the elements of that are added
/// to the returned list, before moving on to the next element.
- List<T> get flattenedToList => [
- for (final elements in this) ...elements,
- ];
+ List<T> get flattenedToList => [for (final elements in this) ...elements];
/// The unique sequential elements of each iterable in this iterable.
///
@@ -909,9 +919,7 @@
/// For each one, which is itself an iterable,
/// all the elements of that are added
/// to the returned set, before moving on to the next element.
- Set<T> get flattenedToSet => {
- for (final elements in this) ...elements,
- };
+ Set<T> get flattenedToSet => {for (final elements in this) ...elements};
}
/// Extension on iterables of [MapEntry].
diff --git a/pkgs/collection/lib/src/iterable_zip.dart b/pkgs/collection/lib/src/iterable_zip.dart
index 9671eaf..10af167 100644
--- a/pkgs/collection/lib/src/iterable_zip.dart
+++ b/pkgs/collection/lib/src/iterable_zip.dart
@@ -42,8 +42,11 @@
return false;
}
}
- _current = List.generate(_iterators.length, (i) => _iterators[i].current,
- growable: false);
+ _current = List.generate(
+ _iterators.length,
+ (i) => _iterators[i].current,
+ growable: false,
+ );
return true;
}
diff --git a/pkgs/collection/lib/src/list_extensions.dart b/pkgs/collection/lib/src/list_extensions.dart
index 40fa8af..a301a1e 100644
--- a/pkgs/collection/lib/src/list_extensions.dart
+++ b/pkgs/collection/lib/src/list_extensions.dart
@@ -36,10 +36,20 @@
/// If [start] and [end] are supplied, only the list range from [start] to
/// [end] is searched, and only that range needs to be sorted.
int binarySearchByCompare<K>(
- E element, K Function(E element) keyOf, int Function(K, K) compare,
- [int start = 0, int? end]) =>
+ E element,
+ K Function(E element) keyOf,
+ int Function(K, K) compare, [
+ int start = 0,
+ int? end,
+ ]) =>
algorithms.binarySearchBy<E, K>(
- this, keyOf, compare, element, start, end);
+ this,
+ keyOf,
+ compare,
+ element,
+ start,
+ end,
+ );
/// Returns the index of [element] in this sorted list.
///
@@ -53,9 +63,19 @@
/// If [start] and [end] are supplied, only the list range from [start] to
/// [end] is searched, and only that range needs to be sorted.
int binarySearchBy<K extends Comparable<K>>(
- E element, K Function(E element) keyOf, [int start = 0, int? end]) =>
+ E element,
+ K Function(E element) keyOf, [
+ int start = 0,
+ int? end,
+ ]) =>
algorithms.binarySearchBy<E, K>(
- this, keyOf, (a, b) => a.compareTo(b), element, start, end);
+ this,
+ keyOf,
+ (a, b) => a.compareTo(b),
+ element,
+ start,
+ end,
+ );
/// Returns the index where [element] should be in this sorted list.
///
@@ -88,8 +108,12 @@
/// If [start] and [end] are supplied, only that range is searched,
/// and only that range need to be sorted.
int lowerBoundByCompare<K>(
- E element, K Function(E) keyOf, int Function(K, K) compare,
- [int start = 0, int? end]) =>
+ E element,
+ K Function(E) keyOf,
+ int Function(K, K) compare, [
+ int start = 0,
+ int? end,
+ ]) =>
algorithms.lowerBoundBy(this, keyOf, compare, element, start, end);
/// Returns the index where [element] should be in this sorted list.
@@ -108,10 +132,20 @@
///
/// If [start] and [end] are supplied, only that range is searched,
/// and only that range need to be sorted.
- int lowerBoundBy<K extends Comparable<K>>(E element, K Function(E) keyOf,
- [int start = 0, int? end]) =>
+ int lowerBoundBy<K extends Comparable<K>>(
+ E element,
+ K Function(E) keyOf, [
+ int start = 0,
+ int? end,
+ ]) =>
algorithms.lowerBoundBy<E, K>(
- this, keyOf, compareComparable, element, start, end);
+ this,
+ keyOf,
+ compareComparable,
+ element,
+ start,
+ end,
+ );
/// Takes an action for each element.
///
@@ -172,7 +206,8 @@
/// Like [Iterable.expand] except that the callback function is supplied with
/// both the index and the element.
Iterable<R> expandIndexed<R>(
- Iterable<R> Function(int index, E element) expand) sync* {
+ Iterable<R> Function(int index, E element) expand,
+ ) sync* {
for (var index = 0; index < length; index++) {
yield* expand(index, this[index]);
}
@@ -187,16 +222,22 @@
///
/// Sorts elements from [start] to [end], defaulting to the entire list.
void sortByCompare<K>(
- K Function(E element) keyOf, int Function(K a, K b) compare,
- [int start = 0, int? end]) {
+ K Function(E element) keyOf,
+ int Function(K a, K b) compare, [
+ int start = 0,
+ int? end,
+ ]) {
quickSortBy(this, keyOf, compare, start, end);
}
/// Sorts elements by the natural order of their [keyOf] property.
///
/// Sorts elements from [start] to [end], defaulting to the entire list.
- void sortBy<K extends Comparable<K>>(K Function(E element) keyOf,
- [int start = 0, int? end]) {
+ void sortBy<K extends Comparable<K>>(
+ K Function(E element) keyOf, [
+ int start = 0,
+ int? end,
+ ]) {
quickSortBy<E, K>(this, keyOf, compareComparable, start, end);
}
@@ -301,7 +342,11 @@
/// Returns -1 if [element] does not occur in this list.
int binarySearch(E element, [int Function(E, E)? compare]) =>
algorithms.binarySearchBy<E, E>(
- this, identity, compare ?? compareComparable, element);
+ this,
+ identity,
+ compare ?? compareComparable,
+ element,
+ );
/// Returns the index where [element] should be in this sorted list.
///
@@ -316,7 +361,11 @@
/// sorted.
int lowerBound(E element, [int Function(E, E)? compare]) =>
algorithms.lowerBoundBy<E, E>(
- this, identity, compare ?? compareComparable, element);
+ this,
+ identity,
+ compare ?? compareComparable,
+ element,
+ );
/// Sort a range of elements by [compare].
///
@@ -325,7 +374,12 @@
void sortRange(int start, int end, [int Function(E a, E b)? compare]) {
RangeError.checkValidRange(start, end, length);
algorithms.quickSortBy<E, E>(
- this, identity, compare ?? compareComparable, start, end);
+ this,
+ identity,
+ compare ?? compareComparable,
+ start,
+ end,
+ );
}
}
diff --git a/pkgs/collection/lib/src/priority_queue.dart b/pkgs/collection/lib/src/priority_queue.dart
index df5b43b..3bf1517 100644
--- a/pkgs/collection/lib/src/priority_queue.dart
+++ b/pkgs/collection/lib/src/priority_queue.dart
@@ -47,8 +47,9 @@
/// as the comparison function, or use a more specialized function
/// if one is available.
factory PriorityQueue.of(
- Iterable<E> elements, int Function(E, E) comparison) =
- HeapPriorityQueue<E>.of;
+ Iterable<E> elements,
+ int Function(E, E) comparison,
+ ) = HeapPriorityQueue<E>.of;
/// Number of elements in the queue.
int get length;
diff --git a/pkgs/collection/lib/src/queue_list.dart b/pkgs/collection/lib/src/queue_list.dart
index a3eaba1..f92dbd2 100644
--- a/pkgs/collection/lib/src/queue_list.dart
+++ b/pkgs/collection/lib/src/queue_list.dart
@@ -163,8 +163,9 @@
if (value < 0) throw RangeError('Length $value may not be negative.');
if (value > length && null is! E) {
throw UnsupportedError(
- 'The length can only be increased when the element type is '
- 'nullable, but the current element type is `$E`.');
+ 'The length can only be increased when the element type is '
+ 'nullable, but the current element type is `$E`.',
+ );
}
var delta = value - length;
diff --git a/pkgs/collection/test/algorithms_test.dart b/pkgs/collection/test/algorithms_test.dart
index 4bc1d54..b5a03fb 100644
--- a/pkgs/collection/test/algorithms_test.dart
+++ b/pkgs/collection/test/algorithms_test.dart
@@ -50,15 +50,21 @@
var l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var c = l.toList();
shuffle(l, 4, 12);
- expect(const IterableEquality().equals(l.getRange(0, 4), c.getRange(0, 4)),
- isTrue);
expect(
- const IterableEquality().equals(l.getRange(12, 16), c.getRange(12, 16)),
- isTrue);
+ const IterableEquality().equals(l.getRange(0, 4), c.getRange(0, 4)),
+ isTrue,
+ );
expect(
- const UnorderedIterableEquality()
- .equals(l.getRange(4, 12), c.getRange(4, 12)),
- isTrue);
+ const IterableEquality().equals(l.getRange(12, 16), c.getRange(12, 16)),
+ isTrue,
+ );
+ expect(
+ const UnorderedIterableEquality().equals(
+ l.getRange(4, 12),
+ c.getRange(4, 12),
+ ),
+ isTrue,
+ );
});
test('binsearch0', () {
@@ -157,14 +163,16 @@
expect(lowerBound(l2, C(5), compare: compareC), equals(1));
});
- void testSort(String name,
- void Function(List<int> elements, [int? start, int? end]) sort) {
+ void testSort(
+ String name,
+ void Function(List<int> elements, [int? start, int? end]) sort,
+ ) {
test('${name}Random', () {
var random = Random();
for (var i = 0; i < 250; i += 10) {
var list = [
for (var j = 0; j < i; j++)
- random.nextInt(25) // Expect some equal elements.
+ random.nextInt(25), // Expect some equal elements.
];
sort(list);
for (var j = 1; j < i; j++) {
@@ -204,8 +212,12 @@
insertionSortBy(list, intId, intCompare, start ?? 0, end ?? list.length);
});
testSort('mergeSort compare', (list, [start, end]) {
- mergeSort(list,
- start: start ?? 0, end: end ?? list.length, compare: intCompare);
+ mergeSort(
+ list,
+ start: start ?? 0,
+ end: end ?? list.length,
+ compare: intCompare,
+ );
});
testSort('mergeSort comparable', (list, [start, end]) {
mergeSort(list, start: start ?? 0, end: end ?? list.length);
@@ -262,11 +274,15 @@
});
void testSortBy(
- String name,
- void Function<T, K>(List<T> elements, K Function(T element) keyOf,
- int Function(K a, K b) compare,
- [int start, int end])
- sort) {
+ String name,
+ void Function<T, K>(
+ List<T> elements,
+ K Function(T element) keyOf,
+ int Function(K a, K b) compare, [
+ int start,
+ int end,
+ ]) sort,
+ ) {
for (var n in [0, 1, 2, 10, 75, 250]) {
var name2 = name;
test('$name2: Same #$n', () {
@@ -321,7 +337,7 @@
// collisions are guaranteed. These should be sorted so that the 'order'
// part of the objects are still in order.
var list = [
- for (var i = 0; i < size; i++) OC(random.nextInt(size >> 2), i)
+ for (var i = 0; i < size; i++) OC(random.nextInt(size >> 2), i),
];
mergeSort(list);
var prev = list[0];
@@ -337,8 +353,12 @@
List copy = list.toList();
var min = size >> 2;
var max = size - min;
- mergeSort<OC>(list,
- start: min, end: max, compare: (a, b) => b.compareTo(a));
+ mergeSort<OC>(
+ list,
+ start: min,
+ end: max,
+ compare: (a, b) => b.compareTo(a),
+ );
prev = list[min];
for (var i = min + 1; i < max; i++) {
var next = list[i];
@@ -369,18 +389,20 @@
expect(l, equals([2, 1, 4, 3, 6, 5]));
});
- test('mergeSort works when runtime generic is a subtype of the static type',
- () {
- // Regression test for https://github.com/dart-lang/collection/issues/317
- final length = 1000; // Larger than _mergeSortLimit
- // Out of order list, with first half guaranteed to empty first during
- // merge.
- final list = [
- for (var i = 0; i < length / 2; i++) -i,
- for (var i = 0; i < length / 2; i++) i + length,
- ];
- expect(() => mergeSort<num>(list), returnsNormally);
- });
+ test(
+ 'mergeSort works when runtime generic is a subtype of the static type',
+ () {
+ // Regression test for https://github.com/dart-lang/collection/issues/317
+ final length = 1000; // Larger than _mergeSortLimit
+ // Out of order list, with first half guaranteed to empty first during
+ // merge.
+ final list = [
+ for (var i = 0; i < length / 2; i++) -i,
+ for (var i = 0; i < length / 2; i++) i + length,
+ ];
+ expect(() => mergeSort<num>(list), returnsNormally);
+ },
+ );
}
class C {
@@ -409,8 +431,12 @@
/// Check that a list is sorted according to [compare] of [keyOf] of elements.
void expectSorted<T, K>(
- List<T> list, K Function(T element) keyOf, int Function(K a, K b) compare,
- [int start = 0, int? end]) {
+ List<T> list,
+ K Function(T element) keyOf,
+ int Function(K a, K b) compare, [
+ int start = 0,
+ int? end,
+]) {
end ??= list.length;
if (start == end) return;
var prev = keyOf(list[start]);
diff --git a/pkgs/collection/test/boollist_test.dart b/pkgs/collection/test/boollist_test.dart
index da7b736..821012e 100644
--- a/pkgs/collection/test/boollist_test.dart
+++ b/pkgs/collection/test/boollist_test.dart
@@ -28,10 +28,7 @@
});
test('BoolList.generate()', () {
- expect(
- BoolList.generate(1024, generator),
- List.generate(1024, generator),
- );
+ expect(BoolList.generate(1024, generator), List.generate(1024, generator));
});
test('BoolList.of()', () {
diff --git a/pkgs/collection/test/canonicalized_map_test.dart b/pkgs/collection/test/canonicalized_map_test.dart
index aadb734..1d1b421 100644
--- a/pkgs/collection/test/canonicalized_map_test.dart
+++ b/pkgs/collection/test/canonicalized_map_test.dart
@@ -61,8 +61,10 @@
test('canonicalizes keys for putIfAbsent', () {
map['1'] = 'value';
- expect(map.putIfAbsent('01', () => throw Exception("shouldn't run")),
- equals('value'));
+ expect(
+ map.putIfAbsent('01', () => throw Exception("shouldn't run")),
+ equals('value'),
+ );
expect(map.putIfAbsent('2', () => 'new value'), equals('new value'));
});
@@ -125,18 +127,18 @@
});
test('values returns all values in the map', () {
- map.addAll(
- {'1': 'value 1', '01': 'value 01', '2': 'value 2', '03': 'value 03'});
+ map.addAll({
+ '1': 'value 1',
+ '01': 'value 01',
+ '2': 'value 2',
+ '03': 'value 03',
+ });
expect(map.values, equals(['value 01', 'value 2', 'value 03']));
});
test('entries returns all key-value pairs in the map', () {
- map.addAll({
- '1': 'value 1',
- '01': 'value 01',
- '2': 'value 2',
- });
+ map.addAll({'1': 'value 1', '01': 'value 01', '2': 'value 2'});
var entries = map.entries.toList();
expect(entries[0].key, '01');
@@ -162,8 +164,10 @@
group('CanonicalizedMap builds an informative string representation', () {
dynamic map;
setUp(() {
- map = CanonicalizedMap<int, String, dynamic>(int.parse,
- isValidKey: RegExp(r'^\d+$').hasMatch);
+ map = CanonicalizedMap<int, String, dynamic>(
+ int.parse,
+ isValidKey: RegExp(r'^\d+$').hasMatch,
+ );
});
test('for an empty map', () {
@@ -176,10 +180,16 @@
});
test('for a map with multiple values', () {
- map.addAll(
- {'1': 'value 1', '01': 'value 01', '2': 'value 2', '03': 'value 03'});
+ map.addAll({
+ '1': 'value 1',
+ '01': 'value 01',
+ '2': 'value 2',
+ '03': 'value 03',
+ });
expect(
- map.toString(), equals('{01: value 01, 2: value 2, 03: value 03}'));
+ map.toString(),
+ equals('{01: value 01, 2: value 2, 03: value 03}'),
+ );
});
test('for a map with a loop', () {
@@ -190,16 +200,22 @@
group('CanonicalizedMap.from', () {
test('canonicalizes its keys', () {
- var map = CanonicalizedMap.from(
- {'1': 'value 1', '2': 'value 2', '3': 'value 3'}, int.parse);
+ var map = CanonicalizedMap.from({
+ '1': 'value 1',
+ '2': 'value 2',
+ '3': 'value 3',
+ }, int.parse);
expect(map['01'], equals('value 1'));
expect(map['02'], equals('value 2'));
expect(map['03'], equals('value 3'));
});
test('uses the final value for collisions', () {
- var map = CanonicalizedMap.from(
- {'1': 'value 1', '01': 'value 2', '001': 'value 3'}, int.parse);
+ var map = CanonicalizedMap.from({
+ '1': 'value 1',
+ '01': 'value 2',
+ '001': 'value 3',
+ }, int.parse);
expect(map.length, equals(1));
expect(map['0001'], equals('value 3'));
});
@@ -208,7 +224,9 @@
group('CanonicalizedMap.fromEntries', () {
test('canonicalizes its keys', () {
var map = CanonicalizedMap.fromEntries(
- {'1': 'value 1', '2': 'value 2', '3': 'value 3'}.entries, int.parse);
+ {'1': 'value 1', '2': 'value 2', '3': 'value 3'}.entries,
+ int.parse,
+ );
expect(map['01'], equals('value 1'));
expect(map['02'], equals('value 2'));
expect(map['03'], equals('value 3'));
@@ -216,8 +234,9 @@
test('uses the final value for collisions', () {
var map = CanonicalizedMap.fromEntries(
- {'1': 'value 1', '01': 'value 2', '001': 'value 3'}.entries,
- int.parse);
+ {'1': 'value 1', '01': 'value 2', '001': 'value 3'}.entries,
+ int.parse,
+ );
expect(map.length, equals(1));
expect(map['0001'], equals('value 3'));
});
@@ -225,8 +244,11 @@
group('CanonicalizedMap.toMapOfCanonicalKeys', () {
test('convert to a `Map<C,V>`', () {
- var map = CanonicalizedMap.from(
- {'1': 'value 1', '2': 'value 2', '3': 'value 3'}, int.parse);
+ var map = CanonicalizedMap.from({
+ '1': 'value 1',
+ '2': 'value 2',
+ '3': 'value 3',
+ }, int.parse);
var map2 = map.toMapOfCanonicalKeys();
@@ -242,8 +264,11 @@
group('CanonicalizedMap.toMap', () {
test('convert to a `Map<K,V>`', () {
- var map = CanonicalizedMap.from(
- {'1': 'value 1', '2': 'value 2', '3': 'value 3'}, int.parse);
+ var map = CanonicalizedMap.from({
+ '1': 'value 1',
+ '2': 'value 2',
+ '3': 'value 3',
+ }, int.parse);
var map2 = map.toMap();
@@ -259,8 +284,11 @@
group('CanonicalizedMap.copy', () {
test('copy instance', () {
- var map = CanonicalizedMap.from(
- {'1': 'value 1', '2': 'value 2', '3': 'value 3'}, int.parse);
+ var map = CanonicalizedMap.from({
+ '1': 'value 1',
+ '2': 'value 2',
+ '3': 'value 3',
+ }, int.parse);
var map2 = map.copy();
diff --git a/pkgs/collection/test/combined_wrapper/iterable_test.dart b/pkgs/collection/test/combined_wrapper/iterable_test.dart
index d5c90bf..d1f58b2 100644
--- a/pkgs/collection/test/combined_wrapper/iterable_test.dart
+++ b/pkgs/collection/test/combined_wrapper/iterable_test.dart
@@ -16,8 +16,14 @@
});
test('should combine multiple iterables with some empty ones', () {
- var combined =
- CombinedIterableView([iterable1, [], iterable2, [], iterable3, []]);
+ var combined = CombinedIterableView([
+ iterable1,
+ [],
+ iterable2,
+ [],
+ iterable3,
+ [],
+ ]);
expect(combined, [0, 1, 2, 3, 4, 5, 6, 7, 8]);
});
diff --git a/pkgs/collection/test/combined_wrapper/list_test.dart b/pkgs/collection/test/combined_wrapper/list_test.dart
index 2705e39..d392c43 100644
--- a/pkgs/collection/test/combined_wrapper/list_test.dart
+++ b/pkgs/collection/test/combined_wrapper/list_test.dart
@@ -15,10 +15,16 @@
// In every way possible this should test the same as an UnmodifiableListView.
common.testUnmodifiableList(
- concat, CombinedListView([list1, list2, list3]), 'combineLists');
+ concat,
+ CombinedListView([list1, list2, list3]),
+ 'combineLists',
+ );
- common.testUnmodifiableList(concat,
- CombinedListView([list1, [], list2, [], list3, []]), 'combineLists');
+ common.testUnmodifiableList(
+ concat,
+ CombinedListView([list1, [], list2, [], list3, []]),
+ 'combineLists',
+ );
test('should function as an empty list when no lists are passed', () {
var empty = CombinedListView([]);
diff --git a/pkgs/collection/test/combined_wrapper/map_test.dart b/pkgs/collection/test/combined_wrapper/map_test.dart
index 9b9a1a8..4c4f017 100644
--- a/pkgs/collection/test/combined_wrapper/map_test.dart
+++ b/pkgs/collection/test/combined_wrapper/map_test.dart
@@ -23,12 +23,16 @@
// In every way possible this should test the same as an UnmodifiableMapView.
_testReadMap(
- concat, CombinedMapView([map1, map2, map3, map4]), 'CombinedMapView');
+ concat,
+ CombinedMapView([map1, map2, map3, map4]),
+ 'CombinedMapView',
+ );
_testReadMap(
- concat,
- CombinedMapView([map1, {}, map2, {}, map3, {}, map4, {}]),
- 'CombinedMapView (some empty)');
+ concat,
+ CombinedMapView([map1, {}, map2, {}, map3, {}, map4, {}]),
+ 'CombinedMapView (some empty)',
+ );
test('should function as an empty map when no maps are passed', () {
var empty = CombinedMapView([]);
diff --git a/pkgs/collection/test/comparators_test.dart b/pkgs/collection/test/comparators_test.dart
index ab48711..b805bfd 100644
--- a/pkgs/collection/test/comparators_test.dart
+++ b/pkgs/collection/test/comparators_test.dart
@@ -54,7 +54,7 @@
'ab',
'z',
'{',
- '~'
+ '~',
];
List<String> sortedBy(int Function(String, String)? compare) =>
@@ -67,21 +67,27 @@
});
test('compareAsciiLowerCase', () {
- expect(sortedBy(compareAsciiLowerCase), sortedBy((a, b) {
- var delta = a.toLowerCase().compareTo(b.toLowerCase());
- if (delta != 0) return delta;
- if (a == b) return 0;
- return a.compareTo(b);
- }));
+ expect(
+ sortedBy(compareAsciiLowerCase),
+ sortedBy((a, b) {
+ var delta = a.toLowerCase().compareTo(b.toLowerCase());
+ if (delta != 0) return delta;
+ if (a == b) return 0;
+ return a.compareTo(b);
+ }),
+ );
});
test('compareAsciiUpperCase', () {
- expect(sortedBy(compareAsciiUpperCase), sortedBy((a, b) {
- var delta = a.toUpperCase().compareTo(b.toUpperCase());
- if (delta != 0) return delta;
- if (a == b) return 0;
- return a.compareTo(b);
- }));
+ expect(
+ sortedBy(compareAsciiUpperCase),
+ sortedBy((a, b) {
+ var delta = a.toUpperCase().compareTo(b.toUpperCase());
+ if (delta != 0) return delta;
+ if (a == b) return 0;
+ return a.compareTo(b);
+ }),
+ );
});
// Replace any digit sequence by ("0", value, length) as char codes.
@@ -95,27 +101,37 @@
});
test('compareNatural', () {
- expect(sortedBy(compareNatural),
- sortedBy((a, b) => replaceNumbers(a).compareTo(replaceNumbers(b))));
+ expect(
+ sortedBy(compareNatural),
+ sortedBy((a, b) => replaceNumbers(a).compareTo(replaceNumbers(b))),
+ );
});
test('compareAsciiLowerCaseNatural', () {
- expect(sortedBy(compareAsciiLowerCaseNatural), sortedBy((a, b) {
- var delta = replaceNumbers(a.toLowerCase())
- .compareTo(replaceNumbers(b.toLowerCase()));
- if (delta != 0) return delta;
- if (a == b) return 0;
- return a.compareTo(b);
- }));
+ expect(
+ sortedBy(compareAsciiLowerCaseNatural),
+ sortedBy((a, b) {
+ var delta = replaceNumbers(
+ a.toLowerCase(),
+ ).compareTo(replaceNumbers(b.toLowerCase()));
+ if (delta != 0) return delta;
+ if (a == b) return 0;
+ return a.compareTo(b);
+ }),
+ );
});
test('compareAsciiUpperCaseNatural', () {
- expect(sortedBy(compareAsciiUpperCaseNatural), sortedBy((a, b) {
- var delta = replaceNumbers(a.toUpperCase())
- .compareTo(replaceNumbers(b.toUpperCase()));
- if (delta != 0) return delta;
- if (a == b) return 0;
- return a.compareTo(b);
- }));
+ expect(
+ sortedBy(compareAsciiUpperCaseNatural),
+ sortedBy((a, b) {
+ var delta = replaceNumbers(
+ a.toUpperCase(),
+ ).compareTo(replaceNumbers(b.toUpperCase()));
+ if (delta != 0) return delta;
+ if (a == b) return 0;
+ return a.compareTo(b);
+ }),
+ );
});
}
diff --git a/pkgs/collection/test/equality_set_test.dart b/pkgs/collection/test/equality_set_test.dart
index 1022726..76d4ba8 100644
--- a/pkgs/collection/test/equality_set_test.dart
+++ b/pkgs/collection/test/equality_set_test.dart
@@ -35,8 +35,14 @@
var list5 = [1, 2, 3];
var list6 = [1, 2, 3];
- var set = EqualitySet.from(
- const IterableEquality(), [list1, list2, list3, list4, list5, list6]);
+ var set = EqualitySet.from(const IterableEquality(), [
+ list1,
+ list2,
+ list3,
+ list4,
+ list5,
+ list6,
+ ]);
expect(set, contains(same(list1)));
expect(set, contains(same(list2)));
diff --git a/pkgs/collection/test/equality_test.dart b/pkgs/collection/test/equality_test.dart
index ce58df6..bf2368b 100644
--- a/pkgs/collection/test/equality_test.dart
+++ b/pkgs/collection/test/equality_test.dart
@@ -42,14 +42,18 @@
var list4 = [o(1), o(2), o(3), o(4), o(5), o(6)];
expect(const ListEquality().equals(list1, list4), isFalse);
expect(
- const ListEquality(IdentityEquality()).equals(list1, list4), isFalse);
+ const ListEquality(IdentityEquality()).equals(list1, list4),
+ isFalse,
+ );
});
test('ListInequality value', () {
var list5 = [o(1), o(2), o(3), o(4), o(6)];
expect(const ListEquality().equals(list1, list5), isFalse);
expect(
- const ListEquality(IdentityEquality()).equals(list1, list5), isFalse);
+ const ListEquality(IdentityEquality()).equals(list1, list5),
+ isFalse,
+ );
});
test('UnorderedIterableEquality', () {
@@ -62,18 +66,18 @@
var list6 = [o(1), o(3), o(5), o(4), o(2), o(1)];
expect(const UnorderedIterableEquality().equals(list1, list6), isFalse);
expect(
- const UnorderedIterableEquality(IdentityEquality())
- .equals(list1, list6),
- isFalse);
+ const UnorderedIterableEquality(IdentityEquality()).equals(list1, list6),
+ isFalse,
+ );
});
test('UnorderedIterableInequality values', () {
var list7 = [o(1), o(3), o(5), o(4), o(6)];
expect(const UnorderedIterableEquality().equals(list1, list7), isFalse);
expect(
- const UnorderedIterableEquality(IdentityEquality())
- .equals(list1, list7),
- isFalse);
+ const UnorderedIterableEquality(IdentityEquality()).equals(list1, list7),
+ isFalse,
+ );
});
test('SetEquality', () {
@@ -102,19 +106,19 @@
var map1a = {
'x': [o(1), o(2), o(3)],
- 'y': [true, false, null]
+ 'y': [true, false, null],
};
var map1b = {
'x': [o(4), o(5), o(6)],
- 'y': [false, true, null]
+ 'y': [false, true, null],
};
var map2a = {
'x': [o(3), o(2), o(1)],
- 'y': [false, true, null]
+ 'y': [false, true, null],
};
var map2b = {
'x': [o(6), o(5), o(4)],
- 'y': [null, false, true]
+ 'y': [null, false, true],
};
var l1 = [map1a, map1b];
var l2 = [map2a, map2b];
@@ -204,9 +208,13 @@
group('EqualityBy should use a derived value for ', () {
var firstEquality = EqualityBy<List<String>, String>((e) => e.first);
var firstInsensitiveEquality = EqualityBy<List<String>, String>(
- (e) => e.first, const CaseInsensitiveEquality());
+ (e) => e.first,
+ const CaseInsensitiveEquality(),
+ );
var firstObjectEquality = EqualityBy<List<Object>, Object>(
- (e) => e.first, const IterableEquality());
+ (e) => e.first,
+ const IterableEquality(),
+ );
test('equality', () {
expect(firstEquality.equals(['foo', 'foo'], ['foo', 'bar']), isTrue);
@@ -223,8 +231,10 @@
});
test('hash with an inner equality', () {
- expect(firstInsensitiveEquality.hash(['fOo']),
- const CaseInsensitiveEquality().hash('foo'));
+ expect(
+ firstInsensitiveEquality.hash(['fOo']),
+ const CaseInsensitiveEquality().hash('foo'),
+ );
});
test('isValidKey', () {
diff --git a/pkgs/collection/test/extensions_test.dart b/pkgs/collection/test/extensions_test.dart
index dd92059..16878a3 100644
--- a/pkgs/collection/test/extensions_test.dart
+++ b/pkgs/collection/test/extensions_test.dart
@@ -18,12 +18,16 @@
expect(iterable([1, 3, 5]).whereNot((e) => e.isOdd), isEmpty);
});
test('all', () {
- expect(iterable([1, 3, 5]).whereNot((e) => e.isEven),
- iterable([1, 3, 5]));
+ expect(
+ iterable([1, 3, 5]).whereNot((e) => e.isEven),
+ iterable([1, 3, 5]),
+ );
});
test('some', () {
- expect(iterable([1, 2, 3, 4]).whereNot((e) => e.isEven),
- iterable([1, 3]));
+ expect(
+ iterable([1, 2, 3, 4]).whereNot((e) => e.isEven),
+ iterable([1, 3]),
+ );
});
});
group('.sorted', () {
@@ -48,8 +52,10 @@
var input = iterable([1, 2, 3, 4, 5]);
var copy = [...input];
var shuffled = input.shuffled();
- expect(const UnorderedIterableEquality().equals(input, shuffled),
- isTrue);
+ expect(
+ const UnorderedIterableEquality().equals(input, shuffled),
+ isTrue,
+ );
// Check that the original list isn't touched
expect(input, copy);
});
@@ -68,17 +74,24 @@
group('.sortedByCompare', () {
test('empty', () {
expect(
- iterable(<int>[]).sortedByCompare(unreachable, unreachable), []);
+ iterable(<int>[]).sortedByCompare(unreachable, unreachable),
+ [],
+ );
});
test('singleton', () {
- expect(iterable(<int>[2]).sortedByCompare(unreachable, unreachable),
- [2]);
+ expect(iterable(<int>[2]).sortedByCompare(unreachable, unreachable), [
+ 2,
+ ]);
});
test('multiple', () {
expect(
- iterable(<int>[30, 2, 100])
- .sortedByCompare(toString, cmpParseInverse),
- [100, 30, 2]);
+ iterable(<int>[
+ 30,
+ 2,
+ 100,
+ ]).sortedByCompare(toString, cmpParseInverse),
+ [100, 30, 2],
+ );
});
});
group('isSorted', () {
@@ -121,33 +134,45 @@
});
group('.isSortedByCompare', () {
test('empty', () {
- expect(iterable(<int>[]).isSortedByCompare(unreachable, unreachable),
- true);
+ expect(
+ iterable(<int>[]).isSortedByCompare(unreachable, unreachable),
+ true,
+ );
});
test('single', () {
expect(iterable([1]).isSortedByCompare(toString, unreachable), true);
});
test('same', () {
- expect(iterable([1, 1, 1, 1]).isSortedByCompare(toString, cmpParse),
- true);
+ expect(
+ iterable([1, 1, 1, 1]).isSortedByCompare(toString, cmpParse),
+ true,
+ );
});
test('multiple', () {
- expect(iterable([1, 2, 3, 4]).isSortedByCompare(toString, cmpParse),
- true);
expect(
- iterable([4, 3, 2, 1])
- .isSortedByCompare(toString, cmpParseInverse),
- true);
+ iterable([1, 2, 3, 4]).isSortedByCompare(toString, cmpParse),
+ true,
+ );
expect(
- iterable([1000, 200, 30, 4])
- .isSortedByCompare(toString, cmpString),
- true);
- expect(iterable([1, 2, 3, 0]).isSortedByCompare(toString, cmpParse),
- false);
- expect(iterable([4, 1, 2, 3]).isSortedByCompare(toString, cmpParse),
- false);
- expect(iterable([4, 3, 2, 1]).isSortedByCompare(toString, cmpParse),
- false);
+ iterable([4, 3, 2, 1]).isSortedByCompare(toString, cmpParseInverse),
+ true,
+ );
+ expect(
+ iterable([1000, 200, 30, 4]).isSortedByCompare(toString, cmpString),
+ true,
+ );
+ expect(
+ iterable([1, 2, 3, 0]).isSortedByCompare(toString, cmpParse),
+ false,
+ );
+ expect(
+ iterable([4, 1, 2, 3]).isSortedByCompare(toString, cmpParse),
+ false,
+ );
+ expect(
+ iterable([4, 3, 2, 1]).isSortedByCompare(toString, cmpParse),
+ false,
+ );
});
});
group('.forEachIndexed', () {
@@ -280,7 +305,7 @@
test('multiple', () {
expect(iterable(<String>['a', 'b']).mapIndexed((i, s) => [i, s]), [
[0, 'a'],
- [1, 'b']
+ [1, 'b'],
]);
});
});
@@ -298,18 +323,29 @@
}
expect(
- iterable(<int>[1, 3, 5, 7])
- .whereIndexed((i, x) => log(i, x).isEven),
- isEmpty);
+ iterable(<int>[
+ 1,
+ 3,
+ 5,
+ 7,
+ ]).whereIndexed((i, x) => log(i, x).isEven),
+ isEmpty,
+ );
expect(trace, [0, 1, 1, 3, 2, 5, 3, 7]);
});
test('all', () {
- expect(iterable(<int>[1, 3, 5, 7]).whereIndexed((i, x) => x.isOdd),
- [1, 3, 5, 7]);
+ expect(iterable(<int>[1, 3, 5, 7]).whereIndexed((i, x) => x.isOdd), [
+ 1,
+ 3,
+ 5,
+ 7,
+ ]);
});
test('some', () {
- expect(iterable(<int>[1, 3, 5, 7]).whereIndexed((i, x) => i.isOdd),
- [3, 7]);
+ expect(iterable(<int>[1, 3, 5, 7]).whereIndexed((i, x) => i.isOdd), [
+ 3,
+ 7,
+ ]);
});
});
group('.whereNotIndexed', () {
@@ -326,19 +362,27 @@
}
expect(
- iterable(<int>[1, 3, 5, 7])
- .whereNotIndexed((i, x) => log(i, x).isOdd),
- isEmpty);
+ iterable(<int>[
+ 1,
+ 3,
+ 5,
+ 7,
+ ]).whereNotIndexed((i, x) => log(i, x).isOdd),
+ isEmpty,
+ );
expect(trace, [0, 1, 1, 3, 2, 5, 3, 7]);
});
test('all', () {
expect(
- iterable(<int>[1, 3, 5, 7]).whereNotIndexed((i, x) => x.isEven),
- [1, 3, 5, 7]);
+ iterable(<int>[1, 3, 5, 7]).whereNotIndexed((i, x) => x.isEven),
+ [1, 3, 5, 7],
+ );
});
test('some', () {
- expect(iterable(<int>[1, 3, 5, 7]).whereNotIndexed((i, x) => i.isOdd),
- [1, 5]);
+ expect(
+ iterable(<int>[1, 3, 5, 7]).whereNotIndexed((i, x) => i.isOdd),
+ [1, 5],
+ );
});
});
group('.expandIndexed', () {
@@ -349,29 +393,42 @@
expect(iterable(['a', 'b']).expandIndexed((i, v) => []), isEmpty);
});
test('larger result', () {
- expect(iterable(['a', 'b']).expandIndexed((i, v) => ['$i', v]),
- ['0', 'a', '1', 'b']);
+ expect(iterable(['a', 'b']).expandIndexed((i, v) => ['$i', v]), [
+ '0',
+ 'a',
+ '1',
+ 'b',
+ ]);
});
test('varying result', () {
expect(
- iterable(['a', 'b'])
- .expandIndexed((i, v) => i.isOdd ? ['$i', v] : []),
- ['1', 'b']);
+ iterable([
+ 'a',
+ 'b',
+ ]).expandIndexed((i, v) => i.isOdd ? ['$i', v] : []),
+ ['1', 'b'],
+ );
});
});
group('.reduceIndexed', () {
test('empty', () {
- expect(() => iterable([]).reduceIndexed((i, a, b) => a),
- throwsStateError);
+ expect(
+ () => iterable([]).reduceIndexed((i, a, b) => a),
+ throwsStateError,
+ );
});
test('single', () {
expect(iterable([1]).reduceIndexed(unreachable), 1);
});
test('multiple', () {
expect(
- iterable([1, 4, 2])
- .reduceIndexed((i, p, v) => p + (pow(i + 1, v) as int)),
- 1 + 16 + 9);
+ iterable([
+ 1,
+ 4,
+ 2,
+ ]).reduceIndexed((i, p, v) => p + (pow(i + 1, v) as int)),
+ 1 + 16 + 9,
+ );
});
});
group('.foldIndexed', () {
@@ -380,11 +437,15 @@
});
test('single', () {
expect(
- iterable([1]).foldIndexed('x', (i, a, b) => '$a:$i:$b'), 'x:0:1');
+ iterable([1]).foldIndexed('x', (i, a, b) => '$a:$i:$b'),
+ 'x:0:1',
+ );
});
test('mulitple', () {
- expect(iterable([1, 3, 9]).foldIndexed('x', (i, a, b) => '$a:$i:$b'),
- 'x:0:1:1:3:2:9');
+ expect(
+ iterable([1, 3, 9]).foldIndexed('x', (i, a, b) => '$a:$i:$b'),
+ 'x:0:1:1:3:2:9',
+ );
});
});
group('.firstWhereOrNull', () {
@@ -407,23 +468,33 @@
});
test('none', () {
expect(
- iterable([1, 3, 7]).firstWhereIndexedOrNull((i, x) => x.isEven),
- null);
- expect(iterable([1, 3, 7]).firstWhereIndexedOrNull((i, x) => i < 0),
- null);
+ iterable([1, 3, 7]).firstWhereIndexedOrNull((i, x) => x.isEven),
+ null,
+ );
+ expect(
+ iterable([1, 3, 7]).firstWhereIndexedOrNull((i, x) => i < 0),
+ null,
+ );
});
test('single', () {
- expect(iterable([0, 3, 6]).firstWhereIndexedOrNull((i, x) => x.isOdd),
- 3);
expect(
- iterable([0, 3, 6]).firstWhereIndexedOrNull((i, x) => i == 1), 3);
+ iterable([0, 3, 6]).firstWhereIndexedOrNull((i, x) => x.isOdd),
+ 3,
+ );
+ expect(
+ iterable([0, 3, 6]).firstWhereIndexedOrNull((i, x) => i == 1),
+ 3,
+ );
});
test('first of multiple', () {
- expect(iterable([0, 3, 7]).firstWhereIndexedOrNull((i, x) => x.isOdd),
- 3);
expect(
- iterable([0, 3, 7]).firstWhereIndexedOrNull((i, x) => i.isEven),
- 0);
+ iterable([0, 3, 7]).firstWhereIndexedOrNull((i, x) => x.isOdd),
+ 3,
+ );
+ expect(
+ iterable([0, 3, 7]).firstWhereIndexedOrNull((i, x) => i.isEven),
+ 0,
+ );
});
});
group('.firstOrNull', () {
@@ -456,22 +527,34 @@
expect(iterable([]).lastWhereIndexedOrNull(unreachable), null);
});
test('none', () {
- expect(iterable([1, 3, 7]).lastWhereIndexedOrNull((i, x) => x.isEven),
- null);
- expect(iterable([1, 3, 7]).lastWhereIndexedOrNull((i, x) => i < 0),
- null);
+ expect(
+ iterable([1, 3, 7]).lastWhereIndexedOrNull((i, x) => x.isEven),
+ null,
+ );
+ expect(
+ iterable([1, 3, 7]).lastWhereIndexedOrNull((i, x) => i < 0),
+ null,
+ );
});
test('single', () {
expect(
- iterable([0, 3, 6]).lastWhereIndexedOrNull((i, x) => x.isOdd), 3);
+ iterable([0, 3, 6]).lastWhereIndexedOrNull((i, x) => x.isOdd),
+ 3,
+ );
expect(
- iterable([0, 3, 6]).lastWhereIndexedOrNull((i, x) => i == 1), 3);
+ iterable([0, 3, 6]).lastWhereIndexedOrNull((i, x) => i == 1),
+ 3,
+ );
});
test('last of multiple', () {
expect(
- iterable([0, 3, 7]).lastWhereIndexedOrNull((i, x) => x.isOdd), 7);
- expect(iterable([0, 3, 7]).lastWhereIndexedOrNull((i, x) => i.isEven),
- 7);
+ iterable([0, 3, 7]).lastWhereIndexedOrNull((i, x) => x.isOdd),
+ 7,
+ );
+ expect(
+ iterable([0, 3, 7]).lastWhereIndexedOrNull((i, x) => i.isEven),
+ 7,
+ );
});
});
group('.lastOrNull', () {
@@ -505,25 +588,33 @@
});
test('none', () {
expect(
- iterable([1, 3, 7]).singleWhereIndexedOrNull((i, x) => x.isEven),
- null);
- expect(iterable([1, 3, 7]).singleWhereIndexedOrNull((i, x) => i < 0),
- null);
+ iterable([1, 3, 7]).singleWhereIndexedOrNull((i, x) => x.isEven),
+ null,
+ );
+ expect(
+ iterable([1, 3, 7]).singleWhereIndexedOrNull((i, x) => i < 0),
+ null,
+ );
});
test('single', () {
expect(
- iterable([0, 3, 6]).singleWhereIndexedOrNull((i, x) => x.isOdd),
- 3);
- expect(iterable([0, 3, 6]).singleWhereIndexedOrNull((i, x) => i == 1),
- 3);
+ iterable([0, 3, 6]).singleWhereIndexedOrNull((i, x) => x.isOdd),
+ 3,
+ );
+ expect(
+ iterable([0, 3, 6]).singleWhereIndexedOrNull((i, x) => i == 1),
+ 3,
+ );
});
test('multiple', () {
expect(
- iterable([0, 3, 7]).singleWhereIndexedOrNull((i, x) => x.isOdd),
- null);
+ iterable([0, 3, 7]).singleWhereIndexedOrNull((i, x) => x.isOdd),
+ null,
+ );
expect(
- iterable([0, 3, 7]).singleWhereIndexedOrNull((i, x) => i.isEven),
- null);
+ iterable([0, 3, 7]).singleWhereIndexedOrNull((i, x) => i.isEven),
+ null,
+ );
});
});
group('.singleOrNull', () {
@@ -542,18 +633,13 @@
expect(iterable([]).lastBy((dynamic _) {}), {});
});
test('single', () {
- expect(iterable([1]).lastBy(toString), {
- '1': 1,
- });
+ expect(iterable([1]).lastBy(toString), {'1': 1});
});
test('multiple', () {
- expect(
- iterable([1, 2, 3, 4, 5]).lastBy((x) => x.isEven),
- {
- false: 5,
- true: 4,
- },
- );
+ expect(iterable([1, 2, 3, 4, 5]).lastBy((x) => x.isEven), {
+ false: 5,
+ true: 4,
+ });
});
});
group('.groupFoldBy', () {
@@ -562,14 +648,17 @@
});
test('single', () {
expect(iterable([1]).groupFoldBy(toString, (p, v) => [p, v]), {
- '1': [null, 1]
+ '1': [null, 1],
});
});
test('multiple', () {
expect(
- iterable([1, 2, 3, 4, 5]).groupFoldBy<bool, String>(
- (x) => x.isEven, (p, v) => p == null ? '$v' : '$p:$v'),
- {true: '2:4', false: '1:3:5'});
+ iterable([1, 2, 3, 4, 5]).groupFoldBy<bool, String>(
+ (x) => x.isEven,
+ (p, v) => p == null ? '$v' : '$p:$v',
+ ),
+ {true: '2:4', false: '1:3:5'},
+ );
});
});
group('.groupSetsBy', () {
@@ -578,14 +667,14 @@
});
test('multiple same', () {
expect(iterable([1, 1]).groupSetsBy(toString), {
- '1': {1}
+ '1': {1},
});
});
test('multiple', () {
expect(iterable([1, 2, 3, 4, 5, 1]).groupSetsBy((x) => x % 3), {
1: {1, 4},
2: {2, 5},
- 0: {3}
+ 0: {3},
});
});
});
@@ -595,14 +684,14 @@
});
test('multiple saame', () {
expect(iterable([1, 1]).groupListsBy(toString), {
- '1': [1, 1]
+ '1': [1, 1],
});
});
test('multiple', () {
expect(iterable([1, 2, 3, 4, 5, 1]).groupListsBy((x) => x % 3), {
1: [1, 4, 1],
2: [2, 5],
- 0: [3]
+ 0: [3],
});
});
});
@@ -612,7 +701,7 @@
});
test('single', () {
expect(iterable([1]).splitBefore(unreachable), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -623,7 +712,7 @@
}
expect(iterable([1, 2, 3]).splitBefore(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, [2, 3]);
});
@@ -631,13 +720,13 @@
expect(iterable([1, 2, 3]).splitBefore((x) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(iterable([1, 2, 3]).splitBefore((x) => x.isEven), [
[1],
- [2, 3]
+ [2, 3],
]);
});
});
@@ -647,7 +736,7 @@
});
test('single', () {
expect(iterable([1]).splitBeforeIndexed(unreachable), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -660,7 +749,7 @@
}
expect(iterable([1, 2, 3]).splitBeforeIndexed(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, ['1', 2, '2', 3]);
});
@@ -668,17 +757,17 @@
expect(iterable([1, 2, 3]).splitBeforeIndexed((i, x) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(iterable([1, 2, 3]).splitBeforeIndexed((i, x) => x.isEven), [
[1],
- [2, 3]
+ [2, 3],
]);
expect(iterable([1, 2, 3]).splitBeforeIndexed((i, x) => i.isEven), [
[1, 2],
- [3]
+ [3],
]);
});
});
@@ -688,10 +777,10 @@
});
test('single', () {
expect(iterable([1]).splitAfter((x) => false), [
- [1]
+ [1],
]);
expect(iterable([1]).splitAfter((x) => true), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -702,7 +791,7 @@
}
expect(iterable([1, 2, 3]).splitAfter(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, [1, 2, 3]);
});
@@ -710,13 +799,13 @@
expect(iterable([1, 2, 3]).splitAfter((x) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(iterable([1, 2, 3]).splitAfter((x) => x.isEven), [
[1, 2],
- [3]
+ [3],
]);
});
});
@@ -726,10 +815,10 @@
});
test('single', () {
expect(iterable([1]).splitAfterIndexed((i, x) => true), [
- [1]
+ [1],
]);
expect(iterable([1]).splitAfterIndexed((i, x) => false), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -742,7 +831,7 @@
}
expect(iterable([1, 2, 3]).splitAfterIndexed(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, ['0', 1, '1', 2, '2', 3]);
});
@@ -750,17 +839,17 @@
expect(iterable([1, 2, 3]).splitAfterIndexed((i, x) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(iterable([1, 2, 3]).splitAfterIndexed((i, x) => x.isEven), [
[1, 2],
- [3]
+ [3],
]);
expect(iterable([1, 2, 3]).splitAfterIndexed((i, x) => i.isEven), [
[1],
- [2, 3]
+ [2, 3],
]);
});
});
@@ -770,7 +859,7 @@
});
test('single', () {
expect(iterable([1]).splitBetween(unreachable), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -781,24 +870,24 @@
}
expect(iterable([1, 2, 3]).splitBetween(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, [
[1, 2],
- [2, 3]
+ [2, 3],
]);
});
test('all splits', () {
expect(iterable([1, 2, 3]).splitBetween((x, y) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(iterable([1, 2, 4]).splitBetween((x, y) => (x ^ y).isEven), [
[1, 2],
- [4]
+ [4],
]);
});
});
@@ -808,7 +897,7 @@
});
test('single', () {
expect(iterable([1]).splitBetweenIndexed(unreachable), [
- [1]
+ [1],
]);
});
test('no split', () {
@@ -819,35 +908,43 @@
}
expect(iterable([1, 2, 3]).splitBetweenIndexed(log), [
- [1, 2, 3]
+ [1, 2, 3],
]);
expect(trace, [
[1, 1, 2],
- [2, 2, 3]
+ [2, 2, 3],
]);
});
test('all splits', () {
expect(iterable([1, 2, 3]).splitBetweenIndexed((i, x, y) => true), [
[1],
[2],
- [3]
+ [3],
]);
});
test('some splits', () {
expect(
- iterable([1, 2, 4])
- .splitBetweenIndexed((i, x, y) => (x ^ y).isEven),
- [
- [1, 2],
- [4]
- ]);
+ iterable([
+ 1,
+ 2,
+ 4,
+ ]).splitBetweenIndexed((i, x, y) => (x ^ y).isEven),
+ [
+ [1, 2],
+ [4],
+ ],
+ );
expect(
- iterable([1, 2, 4])
- .splitBetweenIndexed((i, x, y) => (i ^ y).isEven),
- [
- [1, 2],
- [4]
- ]);
+ iterable([
+ 1,
+ 2,
+ 4,
+ ]).splitBetweenIndexed((i, x, y) => (i ^ y).isEven),
+ [
+ [1, 2],
+ [4],
+ ],
+ );
});
});
group('none', () {
@@ -870,46 +967,45 @@
group('.whereNotNull', () {
test('empty', () {
expect(
- iterable(<int?>[])
- .whereNotNull(), // ignore: deprecated_member_use_from_same_package
- isEmpty);
+ iterable(
+ <int?>[],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ isEmpty,
+ );
});
test('single', () {
expect(
- iterable(<int?>[
- null
- ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package
- isEmpty);
+ iterable(
+ <int?>[null],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ isEmpty,
+ );
expect(
- iterable(<int?>[
- 1
- ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package
- [1]);
+ iterable(
+ <int?>[1],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ [1],
+ );
});
test('multiple', () {
expect(
- iterable(<int?>[
- 1,
- 3,
- 5
- ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package
- [1, 3, 5]);
+ iterable(
+ <int?>[1, 3, 5],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ [1, 3, 5],
+ );
expect(
- iterable(<int?>[
- null,
- null,
- null
- ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package
- isEmpty);
+ iterable(
+ <int?>[null, null, null],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ isEmpty,
+ );
expect(
- iterable(<int?>[
- 1,
- null,
- 3,
- null,
- 5
- ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package
- [1, 3, 5]);
+ iterable(
+ <int?>[1, null, 3, null, 5],
+ ).whereNotNull(), // ignore: deprecated_member_use_from_same_package
+ [1, 3, 5],
+ );
});
});
});
@@ -1049,19 +1145,21 @@
});
test('single value', () {
expect(
- iterable(<Iterable>[
- iterable([1])
- ]).flattened,
- [1]);
+ iterable(<Iterable>[
+ iterable([1]),
+ ]).flattened,
+ [1],
+ );
});
test('multiple', () {
expect(
- iterable(<Iterable>[
- iterable([1, 2]),
- empty,
- iterable([3, 4])
- ]).flattened,
- [1, 2, 3, 4]);
+ iterable(<Iterable>[
+ iterable([1, 2]),
+ empty,
+ iterable([3, 4]),
+ ]).flattened,
+ [1, 2, 3, 4],
+ );
});
});
group('.flattenedToList', () {
@@ -1074,19 +1172,21 @@
});
test('single value', () {
expect(
- iterable(<Iterable>[
- iterable([1])
- ]).flattenedToList,
- [1]);
+ iterable(<Iterable>[
+ iterable([1]),
+ ]).flattenedToList,
+ [1],
+ );
});
test('multiple', () {
expect(
- iterable(<Iterable>[
- iterable([1, 2]),
- empty,
- iterable([3, 4])
- ]).flattenedToList,
- [1, 2, 3, 4]);
+ iterable(<Iterable>[
+ iterable([1, 2]),
+ empty,
+ iterable([3, 4]),
+ ]).flattenedToList,
+ [1, 2, 3, 4],
+ );
});
});
group('.flattenedToSet', () {
@@ -1099,26 +1199,29 @@
});
test('single value', () {
expect(
- iterable(<Iterable>[
- iterable([1])
- ]).flattenedToSet,
- {1});
+ iterable(<Iterable>[
+ iterable([1]),
+ ]).flattenedToSet,
+ {1},
+ );
});
test('multiple', () {
expect(
- iterable(<Iterable>[
- iterable([1, 2]),
- empty,
- iterable([3, 4])
- ]).flattenedToSet,
- {1, 2, 3, 4});
+ iterable(<Iterable>[
+ iterable([1, 2]),
+ empty,
+ iterable([3, 4]),
+ ]).flattenedToSet,
+ {1, 2, 3, 4},
+ );
expect(
- iterable(<Iterable>[
- iterable([1, 2, 3]),
- empty,
- iterable([2, 3, 4])
- ]).flattenedToSet,
- {1, 2, 3, 4});
+ iterable(<Iterable>[
+ iterable([1, 2, 3]),
+ empty,
+ iterable([2, 3, 4]),
+ ]).flattenedToSet,
+ {1, 2, 3, 4},
+ );
});
});
});
@@ -1131,10 +1234,9 @@
);
});
test('single', () {
- expect(
- iterable([const MapEntry('a', 1)]).whereKey((k) => k == 'a'),
- [const MapEntry('a', 1)],
- );
+ expect(iterable([const MapEntry('a', 1)]).whereKey((k) => k == 'a'), [
+ const MapEntry('a', 1),
+ ]);
expect(
iterable([const MapEntry('a', 1)]).whereKey((k) => k == 'b'),
isEmpty,
@@ -1180,10 +1282,9 @@
);
});
test('single', () {
- expect(
- iterable([const MapEntry('a', 1)]).whereValue((v) => v == 1),
- [const MapEntry('a', 1)],
- );
+ expect(iterable([const MapEntry('a', 1)]).whereValue((v) => v == 1), [
+ const MapEntry('a', 1),
+ ]);
expect(
iterable([const MapEntry('a', 1)]).whereValue((v) => v == 2),
isEmpty,
@@ -1352,13 +1453,24 @@
expect(iterable(['a']).sorted(), ['a']);
});
test('multiple', () {
- expect(iterable(<String>['5', '2', '4', '3', '1']).sorted(cmpParse),
- ['1', '2', '3', '4', '5']);
+ expect(iterable(<String>['5', '2', '4', '3', '1']).sorted(cmpParse), [
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ ]);
expect(
- iterable(<String>['5', '2', '4', '3', '1']).sorted(cmpParseInverse),
- ['5', '4', '3', '2', '1']);
- expect(iterable(<String>['5', '2', '4', '3', '1']).sorted(),
- ['1', '2', '3', '4', '5']);
+ iterable(<String>['5', '2', '4', '3', '1']).sorted(cmpParseInverse),
+ ['5', '4', '3', '2', '1'],
+ );
+ expect(iterable(<String>['5', '2', '4', '3', '1']).sorted(), [
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ ]);
// Large enough to trigger quicksort.
var i256 = Iterable<int>.generate(256, (i) => i ^ 0x55);
var sorted256 = [...i256]..sort();
@@ -1454,14 +1566,18 @@
expect(result.length, 10);
expect(result.isSorted(cmpInt), isFalse);
expect(
- const UnorderedIterableEquality().equals(input, result), isTrue);
+ const UnorderedIterableEquality().equals(input, result),
+ isTrue,
+ );
});
test('for overlengthed samples of input', () {
var result = input.sample(20, random);
expect(result.length, 10);
expect(result.isSorted(cmpInt), isFalse);
expect(
- const UnorderedIterableEquality().equals(input, result), isTrue);
+ const UnorderedIterableEquality().equals(input, result),
+ isTrue,
+ );
});
});
});
@@ -1470,8 +1586,10 @@
expect(iterable([]).elementAtOrNull(0), isNull);
});
test('negative index', () async {
- expect(() => iterable([1]).elementAtOrNull(-1),
- throwsA(isA<RangeError>()));
+ expect(
+ () => iterable([1]).elementAtOrNull(-1),
+ throwsA(isA<RangeError>()),
+ );
});
test('index within range', () async {
expect(iterable([1]).elementAtOrNull(0), 1);
@@ -1486,24 +1604,24 @@
});
test('with the same length as the iterable', () {
expect(iterable([1, 2, 3]).slices(3), [
- [1, 2, 3]
+ [1, 2, 3],
]);
});
test('with a longer length than the iterable', () {
expect(iterable([1, 2, 3]).slices(5), [
- [1, 2, 3]
+ [1, 2, 3],
]);
});
test('with a shorter length than the iterable', () {
expect(iterable([1, 2, 3]).slices(2), [
[1, 2],
- [3]
+ [3],
]);
});
test('with length divisible by the iterable\'s', () {
expect(iterable([1, 2, 3, 4]).slices(2), [
[1, 2],
- [3, 4]
+ [3, 4],
]);
});
test('refuses negative length', () {
@@ -1596,12 +1714,20 @@
});
test('multiple', () {
expect(
- [1, 2, 3, 4, 5, 6].binarySearchByCompare(3, toString, cmpParse),
- 2);
+ [1, 2, 3, 4, 5, 6].binarySearchByCompare(3, toString, cmpParse),
+ 2,
+ );
expect(
- [6, 5, 4, 3, 2, 1]
- .binarySearchByCompare(3, toString, cmpParseInverse),
- 3);
+ [
+ 6,
+ 5,
+ 4,
+ 3,
+ 2,
+ 1,
+ ].binarySearchByCompare(3, toString, cmpParseInverse),
+ 3,
+ );
});
});
group('.binarySearchBy', () {
@@ -1645,15 +1771,25 @@
});
test('multiple', () {
expect(
- [1, 2, 3, 4, 5, 6].lowerBoundByCompare(3, toString, cmpParse), 2);
+ [1, 2, 3, 4, 5, 6].lowerBoundByCompare(3, toString, cmpParse),
+ 2,
+ );
expect(
- [6, 5, 4, 3, 2, 1]
- .lowerBoundByCompare(3, toString, cmpParseInverse),
- 3);
+ [
+ 6,
+ 5,
+ 4,
+ 3,
+ 2,
+ 1,
+ ].lowerBoundByCompare(3, toString, cmpParseInverse),
+ 3,
+ );
expect([1, 2, 4, 5, 6].lowerBoundByCompare(3, toString, cmpParse), 2);
expect(
- [6, 5, 4, 2, 1].lowerBoundByCompare(3, toString, cmpParseInverse),
- 3);
+ [6, 5, 4, 2, 1].lowerBoundByCompare(3, toString, cmpParseInverse),
+ 3,
+ );
});
});
group('.lowerBoundBy', () {
@@ -1723,8 +1859,13 @@
expect([5, 7, 4, 2, 3]..sortBy(unreachable, 2, 3), [5, 7, 4, 2, 3]);
});
test('multiple', () {
- expect(
- [5, 7, 40, 2, 3]..sortBy((a) => '$a', 1, 4), [5, 2, 40, 7, 3]);
+ expect([5, 7, 40, 2, 3]..sortBy((a) => '$a', 1, 4), [
+ 5,
+ 2,
+ 40,
+ 7,
+ 3,
+ ]);
});
});
});
@@ -1736,33 +1877,44 @@
expect([2]..sortByCompare(unreachable, unreachable), [2]);
});
test('multiple', () {
- expect([30, 2, 100]..sortByCompare(toString, cmpParseInverse),
- [100, 30, 2]);
+ expect([30, 2, 100]..sortByCompare(toString, cmpParseInverse), [
+ 100,
+ 30,
+ 2,
+ ]);
});
group('range', () {
test('errors', () {
- expect(() => [1].sortByCompare(toString, cmpParse, -1, 1),
- throwsArgumentError);
- expect(() => [1].sortByCompare(toString, cmpParse, 0, 2),
- throwsArgumentError);
- expect(() => [1].sortByCompare(toString, cmpParse, 1, 0),
- throwsArgumentError);
+ expect(
+ () => [1].sortByCompare(toString, cmpParse, -1, 1),
+ throwsArgumentError,
+ );
+ expect(
+ () => [1].sortByCompare(toString, cmpParse, 0, 2),
+ throwsArgumentError,
+ );
+ expect(
+ () => [1].sortByCompare(toString, cmpParse, 1, 0),
+ throwsArgumentError,
+ );
});
test('empty', () {
expect(
- [3, 5, 7, 3, 1]..sortByCompare(unreachable, unreachable, 2, 2),
- [3, 5, 7, 3, 1]);
+ [3, 5, 7, 3, 1]..sortByCompare(unreachable, unreachable, 2, 2),
+ [3, 5, 7, 3, 1],
+ );
});
test('singleton', () {
expect(
- [3, 5, 7, 3, 1]..sortByCompare(unreachable, unreachable, 2, 3),
- [3, 5, 7, 3, 1]);
+ [3, 5, 7, 3, 1]..sortByCompare(unreachable, unreachable, 2, 3),
+ [3, 5, 7, 3, 1],
+ );
});
test('multiple', () {
expect(
- [3, 5, 7, 30, 1]
- ..sortByCompare(toString, cmpParseInverse, 1, 4),
- [3, 30, 7, 5, 1]);
+ [3, 5, 7, 30, 1]..sortByCompare(toString, cmpParseInverse, 1, 4),
+ [3, 30, 7, 5, 1],
+ );
});
});
});
@@ -1866,19 +2018,21 @@
expect([1, 2.5, 'a'].equals([1.0, 2.5, 'a']), true);
expect([1, 2.5, 'a'].equals([1.0, 2.5, 'b']), false);
expect(
- [
- [1]
- ].equals([
- [1]
- ]),
- false);
+ [
+ [1],
+ ].equals([
+ [1],
+ ]),
+ false,
+ );
expect(
- [
- [1]
- ].equals([
- [1]
- ], const ListEquality()),
- true);
+ [
+ [1],
+ ].equals([
+ [1],
+ ], const ListEquality()),
+ true,
+ );
});
});
group('.forEachIndexed', () {
@@ -2011,7 +2165,7 @@
test('multiple', () {
expect(<String>['a', 'b'].mapIndexed((i, s) => [i, s]), [
[0, 'a'],
- [1, 'b']
+ [1, 'b'],
]);
});
});
@@ -2028,13 +2182,19 @@
return b;
}
- expect(<int>[1, 3, 5, 7].whereIndexed((i, x) => log(i, x).isEven),
- isEmpty);
+ expect(
+ <int>[1, 3, 5, 7].whereIndexed((i, x) => log(i, x).isEven),
+ isEmpty,
+ );
expect(trace, [0, 1, 1, 3, 2, 5, 3, 7]);
});
test('all', () {
- expect(
- <int>[1, 3, 5, 7].whereIndexed((i, x) => x.isOdd), [1, 3, 5, 7]);
+ expect(<int>[1, 3, 5, 7].whereIndexed((i, x) => x.isOdd), [
+ 1,
+ 3,
+ 5,
+ 7,
+ ]);
});
test('some', () {
expect(<int>[1, 3, 5, 7].whereIndexed((i, x) => i.isOdd), [3, 7]);
@@ -2053,13 +2213,19 @@
return b;
}
- expect(<int>[1, 3, 5, 7].whereNotIndexed((i, x) => log(i, x).isOdd),
- isEmpty);
+ expect(
+ <int>[1, 3, 5, 7].whereNotIndexed((i, x) => log(i, x).isOdd),
+ isEmpty,
+ );
expect(trace, [0, 1, 1, 3, 2, 5, 3, 7]);
});
test('all', () {
- expect(<int>[1, 3, 5, 7].whereNotIndexed((i, x) => x.isEven),
- [1, 3, 5, 7]);
+ expect(<int>[1, 3, 5, 7].whereNotIndexed((i, x) => x.isEven), [
+ 1,
+ 3,
+ 5,
+ 7,
+ ]);
});
test('some', () {
expect(<int>[1, 3, 5, 7].whereNotIndexed((i, x) => i.isOdd), [1, 5]);
@@ -2073,12 +2239,18 @@
expect(['a', 'b'].expandIndexed((i, v) => []), isEmpty);
});
test('larger result', () {
- expect(['a', 'b'].expandIndexed((i, v) => ['$i', v]),
- ['0', 'a', '1', 'b']);
+ expect(['a', 'b'].expandIndexed((i, v) => ['$i', v]), [
+ '0',
+ 'a',
+ '1',
+ 'b',
+ ]);
});
test('varying result', () {
- expect(['a', 'b'].expandIndexed((i, v) => i.isOdd ? ['$i', v] : []),
- ['1', 'b']);
+ expect(['a', 'b'].expandIndexed((i, v) => i.isOdd ? ['$i', v] : []), [
+ '1',
+ 'b',
+ ]);
});
});
group('.elementAtOrNull', () {
@@ -2101,24 +2273,24 @@
});
test('with the same length as the iterable', () {
expect([1, 2, 3].slices(3), [
- [1, 2, 3]
+ [1, 2, 3],
]);
});
test('with a longer length than the iterable', () {
expect([1, 2, 3].slices(5), [
- [1, 2, 3]
+ [1, 2, 3],
]);
});
test('with a shorter length than the iterable', () {
expect([1, 2, 3].slices(2), [
[1, 2],
- [3]
+ [3],
]);
});
test('with length divisible by the iterable\'s', () {
expect([1, 2, 3, 4].slices(2), [
[1, 2],
- [3, 4]
+ [3, 4],
]);
});
test('refuses negative length', () {
@@ -2139,29 +2311,20 @@
expect(['0'].binarySearch('1', cmpString), -1);
expect(['1'].binarySearch('1', cmpString), 0);
expect(['2'].binarySearch('1', cmpString), -1);
- expect(
- ['0'].binarySearch(
- '1',
- ),
- -1);
- expect(
- ['1'].binarySearch(
- '1',
- ),
- 0);
- expect(
- ['2'].binarySearch(
- '1',
- ),
- -1);
+ expect(['0'].binarySearch('1'), -1);
+ expect(['1'].binarySearch('1'), 0);
+ expect(['2'].binarySearch('1'), -1);
});
test('multiple', () {
expect(
- ['1', '2', '3', '4', '5', '6'].binarySearch('3', cmpString), 2);
+ ['1', '2', '3', '4', '5', '6'].binarySearch('3', cmpString),
+ 2,
+ );
expect(['1', '2', '3', '4', '5', '6'].binarySearch('3'), 2);
expect(
- ['6', '5', '4', '3', '2', '1'].binarySearch('3', cmpParseInverse),
- 3);
+ ['6', '5', '4', '3', '2', '1'].binarySearch('3', cmpParseInverse),
+ 3,
+ );
});
});
});
@@ -2181,7 +2344,9 @@
expect(['1', '2', '3', '4', '5', '6'].lowerBound('3', cmpParse), 2);
expect(['1', '2', '3', '4', '5', '6'].lowerBound('3'), 2);
expect(
- ['6', '5', '4', '3', '2', '1'].lowerBound('3', cmpParseInverse), 3);
+ ['6', '5', '4', '3', '2', '1'].lowerBound('3', cmpParseInverse),
+ 3,
+ );
expect(['1', '2', '4', '5', '6'].lowerBound('3', cmpParse), 2);
expect(['1', '2', '4', '5', '6'].lowerBound('3'), 2);
expect(['6', '5', '4', '2', '1'].lowerBound('3', cmpParseInverse), 3);
diff --git a/pkgs/collection/test/functions_test.dart b/pkgs/collection/test/functions_test.dart
index f602303..785a202 100644
--- a/pkgs/collection/test/functions_test.dart
+++ b/pkgs/collection/test/functions_test.dart
@@ -11,10 +11,13 @@
group('mapMap()', () {
test('with an empty map returns an empty map', () {
expect(
- mapMap({},
- key: expectAsync2((_, __) {}, count: 0),
- value: expectAsync2((_, __) {}, count: 0)),
- isEmpty);
+ mapMap(
+ {},
+ key: expectAsync2((_, __) {}, count: 0),
+ value: expectAsync2((_, __) {}, count: 0),
+ ),
+ isEmpty,
+ );
});
test('with no callbacks, returns a copy of the map', () {
@@ -29,50 +32,71 @@
test("maps the map's keys", () {
expect(
- mapMap<String, int, dynamic, int>({'foo': 1, 'bar': 2},
- key: (dynamic key, dynamic value) => key[value]),
- equals({'o': 1, 'r': 2}));
+ mapMap<String, int, dynamic, int>({
+ 'foo': 1,
+ 'bar': 2,
+ }, key: (dynamic key, dynamic value) => key[value]),
+ equals({'o': 1, 'r': 2}),
+ );
});
test("maps the map's values", () {
expect(
- mapMap<String, int, String, dynamic>({'foo': 1, 'bar': 2},
- value: (dynamic key, dynamic value) => key[value]),
- equals({'foo': 'o', 'bar': 'r'}));
+ mapMap<String, int, String, dynamic>({
+ 'foo': 1,
+ 'bar': 2,
+ }, value: (dynamic key, dynamic value) => key[value]),
+ equals({'foo': 'o', 'bar': 'r'}),
+ );
});
test("maps both the map's keys and values", () {
expect(
- mapMap({'foo': 1, 'bar': 2},
- key: (dynamic key, dynamic value) => '$key$value',
- value: (dynamic key, dynamic value) => key[value]),
- equals({'foo1': 'o', 'bar2': 'r'}));
+ mapMap(
+ {'foo': 1, 'bar': 2},
+ key: (dynamic key, dynamic value) => '$key$value',
+ value: (dynamic key, dynamic value) => key[value],
+ ),
+ equals({'foo1': 'o', 'bar2': 'r'}),
+ );
});
});
group('mergeMaps()', () {
test('with empty maps returns an empty map', () {
expect(
- mergeMaps({}, {},
- value: expectAsync2((dynamic _, dynamic __) {}, count: 0)),
- isEmpty);
+ mergeMaps(
+ {},
+ {},
+ value: expectAsync2((dynamic _, dynamic __) {}, count: 0),
+ ),
+ isEmpty,
+ );
});
test('returns a map with all values in both input maps', () {
- expect(mergeMaps({'foo': 1, 'bar': 2}, {'baz': 3, 'qux': 4}),
- equals({'foo': 1, 'bar': 2, 'baz': 3, 'qux': 4}));
+ expect(
+ mergeMaps({'foo': 1, 'bar': 2}, {'baz': 3, 'qux': 4}),
+ equals({'foo': 1, 'bar': 2, 'baz': 3, 'qux': 4}),
+ );
});
test("the second map's values win by default", () {
- expect(mergeMaps({'foo': 1, 'bar': 2}, {'bar': 3, 'baz': 4}),
- equals({'foo': 1, 'bar': 3, 'baz': 4}));
+ expect(
+ mergeMaps({'foo': 1, 'bar': 2}, {'bar': 3, 'baz': 4}),
+ equals({'foo': 1, 'bar': 3, 'baz': 4}),
+ );
});
test('uses the callback to merge values', () {
expect(
- mergeMaps({'foo': 1, 'bar': 2}, {'bar': 3, 'baz': 4},
- value: (dynamic value1, dynamic value2) => value1 + value2),
- equals({'foo': 1, 'bar': 5, 'baz': 4}));
+ mergeMaps(
+ {'foo': 1, 'bar': 2},
+ {'bar': 3, 'baz': 4},
+ value: (dynamic value1, dynamic value2) => value1 + value2,
+ ),
+ equals({'foo': 1, 'bar': 5, 'baz': 4}),
+ );
});
});
@@ -86,13 +110,15 @@
test("keeps the latest element for the function's return value", () {
expect(
- lastBy(['foo', 'bar', 'baz', 'bop', 'qux'],
- (String string) => string[1]),
- equals({
- 'o': 'bop',
- 'a': 'baz',
- 'u': 'qux',
- }));
+ lastBy([
+ 'foo',
+ 'bar',
+ 'baz',
+ 'bop',
+ 'qux',
+ ], (String string) => string[1]),
+ equals({'o': 'bop', 'a': 'baz', 'u': 'qux'}),
+ );
});
});
@@ -103,85 +129,109 @@
test("groups elements by the function's return value", () {
expect(
- groupBy(['foo', 'bar', 'baz', 'bop', 'qux'],
- (dynamic string) => string[1]),
- equals({
- 'o': ['foo', 'bop'],
- 'a': ['bar', 'baz'],
- 'u': ['qux']
- }));
+ groupBy([
+ 'foo',
+ 'bar',
+ 'baz',
+ 'bop',
+ 'qux',
+ ], (dynamic string) => string[1]),
+ equals({
+ 'o': ['foo', 'bop'],
+ 'a': ['bar', 'baz'],
+ 'u': ['qux'],
+ }),
+ );
});
});
group('minBy()', () {
test('returns null for an empty iterable', () {
expect(
- minBy([], expectAsync1((dynamic _) {}, count: 0),
- compare: expectAsync2((dynamic _, dynamic __) => -1, count: 0)),
- isNull);
+ minBy(
+ [],
+ expectAsync1((dynamic _) {}, count: 0),
+ compare: expectAsync2((dynamic _, dynamic __) => -1, count: 0),
+ ),
+ isNull,
+ );
});
test(
'returns the element for which the ordering function returns the '
'smallest value', () {
expect(
- minBy([
- {'foo': 3},
- {'foo': 5},
- {'foo': 4},
- {'foo': 1},
- {'foo': 2}
- ], (dynamic map) => map['foo']),
- equals({'foo': 1}));
+ minBy([
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2},
+ ], (dynamic map) => map['foo']),
+ equals({'foo': 1}),
+ );
});
test('uses a custom comparator if provided', () {
expect(
- minBy<Map<String, int>, Map<String, int>>([
+ minBy<Map<String, int>, Map<String, int>>(
+ [
{'foo': 3},
{'foo': 5},
{'foo': 4},
{'foo': 1},
- {'foo': 2}
- ], (map) => map,
- compare: (map1, map2) => map1['foo']!.compareTo(map2['foo']!)),
- equals({'foo': 1}));
+ {'foo': 2},
+ ],
+ (map) => map,
+ compare: (map1, map2) => map1['foo']!.compareTo(map2['foo']!),
+ ),
+ equals({'foo': 1}),
+ );
});
});
group('maxBy()', () {
test('returns null for an empty iterable', () {
expect(
- maxBy([], expectAsync1((dynamic _) {}, count: 0),
- compare: expectAsync2((dynamic _, dynamic __) => 0, count: 0)),
- isNull);
+ maxBy(
+ [],
+ expectAsync1((dynamic _) {}, count: 0),
+ compare: expectAsync2((dynamic _, dynamic __) => 0, count: 0),
+ ),
+ isNull,
+ );
});
test(
'returns the element for which the ordering function returns the '
'largest value', () {
expect(
- maxBy([
- {'foo': 3},
- {'foo': 5},
- {'foo': 4},
- {'foo': 1},
- {'foo': 2}
- ], (dynamic map) => map['foo']),
- equals({'foo': 5}));
+ maxBy([
+ {'foo': 3},
+ {'foo': 5},
+ {'foo': 4},
+ {'foo': 1},
+ {'foo': 2},
+ ], (dynamic map) => map['foo']),
+ equals({'foo': 5}),
+ );
});
test('uses a custom comparator if provided', () {
expect(
- maxBy<Map<String, int>, Map<String, int>>([
+ maxBy<Map<String, int>, Map<String, int>>(
+ [
{'foo': 3},
{'foo': 5},
{'foo': 4},
{'foo': 1},
- {'foo': 2}
- ], (map) => map,
- compare: (map1, map2) => map1['foo']!.compareTo(map2['foo']!)),
- equals({'foo': 5}));
+ {'foo': 2},
+ ],
+ (map) => map,
+ compare: (map1, map2) => map1['foo']!.compareTo(map2['foo']!),
+ ),
+ equals({'foo': 5}),
+ );
});
});
@@ -192,50 +242,53 @@
test('returns the input when there are no transitive connections', () {
expect(
- transitiveClosure({
- 'foo': ['bar'],
- 'bar': [],
- 'bang': ['qux', 'zap'],
- 'qux': [],
- 'zap': []
- }),
- equals({
- 'foo': ['bar'],
- 'bar': [],
- 'bang': ['qux', 'zap'],
- 'qux': [],
- 'zap': []
- }));
+ transitiveClosure({
+ 'foo': ['bar'],
+ 'bar': [],
+ 'bang': ['qux', 'zap'],
+ 'qux': [],
+ 'zap': [],
+ }),
+ equals({
+ 'foo': ['bar'],
+ 'bar': [],
+ 'bang': ['qux', 'zap'],
+ 'qux': [],
+ 'zap': [],
+ }),
+ );
});
test('flattens transitive connections', () {
expect(
- transitiveClosure({
- 'qux': [],
- 'bar': ['baz'],
- 'baz': ['qux'],
- 'foo': ['bar']
- }),
- equals({
- 'foo': ['bar', 'baz', 'qux'],
- 'bar': ['baz', 'qux'],
- 'baz': ['qux'],
- 'qux': []
- }));
+ transitiveClosure({
+ 'qux': [],
+ 'bar': ['baz'],
+ 'baz': ['qux'],
+ 'foo': ['bar'],
+ }),
+ equals({
+ 'foo': ['bar', 'baz', 'qux'],
+ 'bar': ['baz', 'qux'],
+ 'baz': ['qux'],
+ 'qux': [],
+ }),
+ );
});
test('handles loops', () {
expect(
- transitiveClosure({
- 'foo': ['bar'],
- 'bar': ['baz'],
- 'baz': ['foo']
- }),
- equals({
- 'foo': ['bar', 'baz', 'foo'],
- 'bar': ['baz', 'foo', 'bar'],
- 'baz': ['foo', 'bar', 'baz']
- }));
+ transitiveClosure({
+ 'foo': ['bar'],
+ 'bar': ['baz'],
+ 'baz': ['foo'],
+ }),
+ equals({
+ 'foo': ['bar', 'baz', 'foo'],
+ 'bar': ['baz', 'foo', 'bar'],
+ 'baz': ['foo', 'bar', 'baz'],
+ }),
+ );
});
});
@@ -246,33 +299,36 @@
test('returns one set for a singleton graph', () {
expect(
- stronglyConnectedComponents({'a': []}),
- equals([
- {'a'}
- ]));
+ stronglyConnectedComponents({'a': []}),
+ equals([
+ {'a'},
+ ]),
+ );
});
test('returns two sets for a two-element tree', () {
expect(
- stronglyConnectedComponents({
- 'a': ['b'],
- 'b': []
- }),
- equals([
- {'a'},
- {'b'}
- ]));
+ stronglyConnectedComponents({
+ 'a': ['b'],
+ 'b': [],
+ }),
+ equals([
+ {'a'},
+ {'b'},
+ ]),
+ );
});
test('returns one set for a two-element loop', () {
expect(
- stronglyConnectedComponents({
- 'a': ['b'],
- 'b': ['a']
- }),
- equals([
- {'a', 'b'}
- ]));
+ stronglyConnectedComponents({
+ 'a': ['b'],
+ 'b': ['a'],
+ }),
+ equals([
+ {'a', 'b'},
+ ]),
+ );
});
test('returns individual vertices for a tree', () {
@@ -283,7 +339,7 @@
'baz': ['qux'],
'bang': ['zap'],
'qux': [],
- 'zap': []
+ 'zap': [],
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
@@ -294,22 +350,23 @@
{'bang'},
{'zap'},
{'baz'},
- {'qux'}
+ {'qux'},
]),
);
});
test('returns a single set for a fully cyclic graph', () {
expect(
- stronglyConnectedComponents({
- 'foo': ['bar'],
- 'bar': ['baz'],
- 'baz': ['bang'],
- 'bang': ['foo']
- }),
- equals([
- {'foo', 'bar', 'baz', 'bang'}
- ]));
+ stronglyConnectedComponents({
+ 'foo': ['bar'],
+ 'bar': ['baz'],
+ 'baz': ['bang'],
+ 'bang': ['foo'],
+ }),
+ equals([
+ {'foo', 'bar', 'baz', 'bang'},
+ ]),
+ );
});
test('returns separate sets for each strongly connected component', () {
@@ -323,7 +380,7 @@
'e': ['a', 'f'],
'f': ['g'],
'g': ['f'],
- 'h': ['g', 'd']
+ 'h': ['g', 'd'],
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
@@ -344,7 +401,7 @@
'baz': ['qux'],
'qux': [],
'foo': ['bar'],
- 'bang': ['zap']
+ 'bang': ['zap'],
}),
equals([
// This is expected to return *a* topological ordering, but this isn't
@@ -355,7 +412,7 @@
{'bang'},
{'zap'},
{'baz'},
- {'qux'}
+ {'qux'},
]),
);
});
diff --git a/pkgs/collection/test/ignore_ascii_case_test.dart b/pkgs/collection/test/ignore_ascii_case_test.dart
index 78f54a2..26b89e9 100644
--- a/pkgs/collection/test/ignore_ascii_case_test.dart
+++ b/pkgs/collection/test/ignore_ascii_case_test.dart
@@ -34,8 +34,11 @@
for (var s2 in strings) {
var reason = '$s1 =?= $s2';
expect(equalsIgnoreAsciiCase(s1, s2), true, reason: reason);
- expect(hashIgnoreAsciiCase(s1), hashIgnoreAsciiCase(s2),
- reason: reason);
+ expect(
+ hashIgnoreAsciiCase(s1),
+ hashIgnoreAsciiCase(s2),
+ reason: reason,
+ );
}
}
@@ -44,8 +47,11 @@
expect(equalsIgnoreAsciiCase(upperCaseLetters, lowerCaseLetters), true);
void testChars(String char1, String char2, bool areEqual) {
- expect(equalsIgnoreAsciiCase(char1, char2), areEqual,
- reason: "$char1 ${areEqual ? "=" : "!"}= $char2");
+ expect(
+ equalsIgnoreAsciiCase(char1, char2),
+ areEqual,
+ reason: "$char1 ${areEqual ? "=" : "!"}= $char2",
+ );
}
for (var i = 0; i < upperCaseLetters.length; i++) {
diff --git a/pkgs/collection/test/iterable_zip_test.dart b/pkgs/collection/test/iterable_zip_test.dart
index 3881c6a..ffd1196 100644
--- a/pkgs/collection/test/iterable_zip_test.dart
+++ b/pkgs/collection/test/iterable_zip_test.dart
@@ -14,102 +14,110 @@
void main() {
test('Basic', () {
expect(
- IterableZip([
- [1, 2, 3],
- [4, 5, 6],
- [7, 8, 9]
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9],
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Uneven length 1', () {
expect(
- IterableZip([
- [1, 2, 3, 99, 100],
- [4, 5, 6],
- [7, 8, 9]
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3, 99, 100],
+ [4, 5, 6],
+ [7, 8, 9],
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Uneven length 2', () {
expect(
- IterableZip([
- [1, 2, 3],
- [4, 5, 6, 99, 100],
- [7, 8, 9]
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3],
+ [4, 5, 6, 99, 100],
+ [7, 8, 9],
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Uneven length 3', () {
expect(
- IterableZip([
- [1, 2, 3],
- [4, 5, 6],
- [7, 8, 9, 99, 100]
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9, 99, 100],
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Uneven length 3', () {
expect(
- IterableZip([
- [1, 2, 3, 98],
- [4, 5, 6],
- [7, 8, 9, 99, 100]
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3, 98],
+ [4, 5, 6],
+ [7, 8, 9, 99, 100],
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Empty 1', () {
expect(
- IterableZip([
- [],
- [4, 5, 6],
- [7, 8, 9]
- ]),
- equals([]));
+ IterableZip([
+ [],
+ [4, 5, 6],
+ [7, 8, 9],
+ ]),
+ equals([]),
+ );
});
test('Empty 2', () {
expect(
- IterableZip([
- [1, 2, 3],
- [],
- [7, 8, 9]
- ]),
- equals([]));
+ IterableZip([
+ [1, 2, 3],
+ [],
+ [7, 8, 9],
+ ]),
+ equals([]),
+ );
});
test('Empty 3', () {
expect(
- IterableZip([
- [1, 2, 3],
- [4, 5, 6],
- []
- ]),
- equals([]));
+ IterableZip([
+ [1, 2, 3],
+ [4, 5, 6],
+ [],
+ ]),
+ equals([]),
+ );
});
test('Empty source', () {
@@ -118,14 +126,15 @@
test('Single Source', () {
expect(
- IterableZip([
- [1, 2, 3]
- ]),
- equals([
- [1],
- [2],
- [3]
- ]));
+ IterableZip([
+ [1, 2, 3],
+ ]),
+ equals([
+ [1],
+ [2],
+ [3],
+ ]),
+ );
});
test('Not-lists', () {
@@ -135,75 +144,82 @@
var it3 = {7: 0, 8: 0, 9: 0}.keys;
var allIts = Iterable.generate(3, (i) => [it1, it2, it3][i]);
expect(
- IterableZip(allIts),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip(allIts),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
test('Error 1', () {
expect(
- () => IterableZip([
- iterError([1, 2, 3], 2),
- [4, 5, 6],
- [7, 8, 9]
- ]).toList(),
- throwsA(equals('BAD')));
+ () => IterableZip([
+ iterError([1, 2, 3], 2),
+ [4, 5, 6],
+ [7, 8, 9],
+ ]).toList(),
+ throwsA(equals('BAD')),
+ );
});
test('Error 2', () {
expect(
- () => IterableZip([
- [1, 2, 3],
- iterError([4, 5, 6], 5),
- [7, 8, 9]
- ]).toList(),
- throwsA(equals('BAD')));
+ () => IterableZip([
+ [1, 2, 3],
+ iterError([4, 5, 6], 5),
+ [7, 8, 9],
+ ]).toList(),
+ throwsA(equals('BAD')),
+ );
});
test('Error 3', () {
expect(
- () => IterableZip([
- [1, 2, 3],
- [4, 5, 6],
- iterError([7, 8, 9], 8)
- ]).toList(),
- throwsA(equals('BAD')));
+ () => IterableZip([
+ [1, 2, 3],
+ [4, 5, 6],
+ iterError([7, 8, 9], 8),
+ ]).toList(),
+ throwsA(equals('BAD')),
+ );
});
test('Error at end', () {
expect(
- () => IterableZip([
- [1, 2, 3],
- iterError([4, 5, 6], 6),
- [7, 8, 9]
- ]).toList(),
- throwsA(equals('BAD')));
+ () => IterableZip([
+ [1, 2, 3],
+ iterError([4, 5, 6], 6),
+ [7, 8, 9],
+ ]).toList(),
+ throwsA(equals('BAD')),
+ );
});
test('Error before first end', () {
expect(
- () => IterableZip([
- iterError([1, 2, 3, 4], 4),
- [4, 5, 6],
- [7, 8, 9]
- ]).toList(),
- throwsA(equals('BAD')));
+ () => IterableZip([
+ iterError([1, 2, 3, 4], 4),
+ [4, 5, 6],
+ [7, 8, 9],
+ ]).toList(),
+ throwsA(equals('BAD')),
+ );
});
test('Error after first end', () {
expect(
- IterableZip([
- [1, 2, 3],
- [4, 5, 6],
- iterError([7, 8, 9, 10], 10)
- ]),
- equals([
- [1, 4, 7],
- [2, 5, 8],
- [3, 6, 9]
- ]));
+ IterableZip([
+ [1, 2, 3],
+ [4, 5, 6],
+ iterError([7, 8, 9, 10], 10),
+ ]),
+ equals([
+ [1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9],
+ ]),
+ );
});
}
diff --git a/pkgs/collection/test/priority_queue_test.dart b/pkgs/collection/test/priority_queue_test.dart
index a7aafc4..fb4aefe 100644
--- a/pkgs/collection/test/priority_queue_test.dart
+++ b/pkgs/collection/test/priority_queue_test.dart
@@ -61,14 +61,27 @@
}
void testCustom(
- PriorityQueue<C> Function(int Function(C, C)? comparator) create) {
+ PriorityQueue<C> Function(int Function(C, C)? comparator) create,
+) {
for (var count in [1, 5, 127, 128]) {
- testQueue('Custom:$count/null', () => create(null),
- List<C>.generate(count, C.new), C(count));
- testQueue('Custom:$count/compare', () => create(compare),
- List<C>.generate(count, C.new), C(count));
- testQueue('Custom:$count/compareNeg', () => create(compareNeg),
- List<C>.generate(count, (x) => C(count - x)), const C(0));
+ testQueue(
+ 'Custom:$count/null',
+ () => create(null),
+ List<C>.generate(count, C.new),
+ C(count),
+ );
+ testQueue(
+ 'Custom:$count/compare',
+ () => create(compare),
+ List<C>.generate(count, C.new),
+ C(count),
+ );
+ testQueue(
+ 'Custom:$count/compareNeg',
+ () => create(compareNeg),
+ List<C>.generate(count, (x) => C(count - x)),
+ const C(0),
+ );
}
}
@@ -85,7 +98,10 @@
}
void testQueueBody<T>(
- PriorityQueue<T> Function() create, List<T> elements, T notElement) {
+ PriorityQueue<T> Function() create,
+ List<T> elements,
+ T notElement,
+) {
var q = create();
expect(q.isEmpty, isTrue);
expect(q, hasLength(0));
@@ -339,11 +355,15 @@
var q = HeapPriorityQueue<int>((a, b) => a - b)
..addAll([6, 4, 2, 3, 5, 8]);
var e = q.unorderedElements;
- expect(q.removeFirst(),
- 2); // Modification before creating iterator is not a problem.
+ expect(
+ q.removeFirst(),
+ 2,
+ ); // Modification before creating iterator is not a problem.
var it = e.iterator;
- expect(q.removeFirst(),
- 3); // Modification after creating iterator is a problem.
+ expect(
+ q.removeFirst(),
+ 3,
+ ); // Modification after creating iterator is a problem.
expect(it.moveNext, throwsConcurrentModificationError);
it = e.iterator; // New iterator is not affected.
diff --git a/pkgs/collection/test/queue_list_test.dart b/pkgs/collection/test/queue_list_test.dart
index 1550f92..a2c4d89 100644
--- a/pkgs/collection/test/queue_list_test.dart
+++ b/pkgs/collection/test/queue_list_test.dart
@@ -225,33 +225,45 @@
});
test('add', () {
- expect(() => queue.forEach((_) => queue.add(4)),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.add(4)),
+ throwsConcurrentModificationError,
+ );
});
test('addAll', () {
- expect(() => queue.forEach((_) => queue.addAll([4, 5, 6])),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.addAll([4, 5, 6])),
+ throwsConcurrentModificationError,
+ );
});
test('addFirst', () {
- expect(() => queue.forEach((_) => queue.addFirst(0)),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.addFirst(0)),
+ throwsConcurrentModificationError,
+ );
});
test('removeFirst', () {
- expect(() => queue.forEach((_) => queue.removeFirst()),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.removeFirst()),
+ throwsConcurrentModificationError,
+ );
});
test('removeLast', () {
- expect(() => queue.forEach((_) => queue.removeLast()),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.removeLast()),
+ throwsConcurrentModificationError,
+ );
});
test('length=', () {
- expect(() => queue.forEach((_) => queue.length = 1),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.length = 1),
+ throwsConcurrentModificationError,
+ );
});
});
@@ -259,8 +271,11 @@
var patternQueue = QueueList<Pattern>()..addAll(['a', 'b']);
var stringQueue = patternQueue.cast<String>();
stringQueue.addAll(['c', 'd']);
- expect(stringQueue, const TypeMatcher<QueueList<String>>(),
- reason: 'Expected QueueList<String>, got ${stringQueue.runtimeType}');
+ expect(
+ stringQueue,
+ const TypeMatcher<QueueList<String>>(),
+ reason: 'Expected QueueList<String>, got ${stringQueue.runtimeType}',
+ );
expect(stringQueue, ['a', 'b', 'c', 'd']);
@@ -270,8 +285,11 @@
test('cast throws on mutation when the type is not valid', () {
QueueList<Object> stringQueue = QueueList<String>();
var numQueue = stringQueue.cast<num>();
- expect(numQueue, const TypeMatcher<QueueList<num>>(),
- reason: 'Expected QueueList<num>, got ${numQueue.runtimeType}');
+ expect(
+ numQueue,
+ const TypeMatcher<QueueList<num>>(),
+ reason: 'Expected QueueList<num>, got ${numQueue.runtimeType}',
+ );
expect(() => numQueue.add(1), throwsA(isA<TypeError>()));
});
@@ -303,5 +321,6 @@
/// Returns a matcher that expects that a closure throws a
/// [ConcurrentModificationError].
-final throwsConcurrentModificationError =
- throwsA(const TypeMatcher<ConcurrentModificationError>());
+final throwsConcurrentModificationError = throwsA(
+ const TypeMatcher<ConcurrentModificationError>(),
+);
diff --git a/pkgs/collection/test/union_set_test.dart b/pkgs/collection/test/union_set_test.dart
index d06faf3..76e4913 100644
--- a/pkgs/collection/test/union_set_test.dart
+++ b/pkgs/collection/test/union_set_test.dart
@@ -115,7 +115,7 @@
var set = UnionSet.from([
{duration1},
- {duration2}
+ {duration2},
]);
expect(set.lookup(const Duration(seconds: 0)), same(duration1));
@@ -138,7 +138,7 @@
set = UnionSet.from([
{1, 2},
{5},
- innerSet
+ innerSet,
]);
innerSet.add(4);
@@ -182,7 +182,7 @@
var outerSet = {
{1, 2},
{5},
- innerSet
+ innerSet,
};
set = UnionSet<int>(outerSet);
diff --git a/pkgs/collection/test/unmodifiable_collection_test.dart b/pkgs/collection/test/unmodifiable_collection_test.dart
index 12a9a0a..9d77fa5 100644
--- a/pkgs/collection/test/unmodifiable_collection_test.dart
+++ b/pkgs/collection/test/unmodifiable_collection_test.dart
@@ -94,7 +94,9 @@
test('$name - expand', () {
expect(
- wrapped.expand((x) => [x, x]), equals(original.expand((x) => [x, x])));
+ wrapped.expand((x) => [x, x]),
+ equals(original.expand((x) => [x, x])),
+ );
});
test('$name - first', () {
@@ -109,15 +111,19 @@
if (original.isEmpty) {
expect(() => wrapped.firstWhere((_) => true), throwsStateError);
} else {
- expect(wrapped.firstWhere((_) => true),
- equals(original.firstWhere((_) => true)));
+ expect(
+ wrapped.firstWhere((_) => true),
+ equals(original.firstWhere((_) => true)),
+ );
}
expect(() => wrapped.firstWhere((_) => false), throwsStateError);
});
test('$name - fold', () {
- expect(wrapped.fold(0, (dynamic x, y) => x + y),
- equals(original.fold(0, (dynamic x, y) => x + y)));
+ expect(
+ wrapped.fold(0, (dynamic x, y) => x + y),
+ equals(original.fold(0, (dynamic x, y) => x + y)),
+ );
});
test('$name - forEach', () {
@@ -169,8 +175,10 @@
if (original.isEmpty) {
expect(() => wrapped.lastWhere((_) => true), throwsStateError);
} else {
- expect(wrapped.lastWhere((_) => true),
- equals(original.lastWhere((_) => true)));
+ expect(
+ wrapped.lastWhere((_) => true),
+ equals(original.lastWhere((_) => true)),
+ );
}
expect(() => wrapped.lastWhere((_) => false), throwsStateError);
});
@@ -187,8 +195,10 @@
if (original.isEmpty) {
expect(() => wrapped.reduce((x, y) => x + y), throwsStateError);
} else {
- expect(wrapped.reduce((x, y) => x + y),
- equals(original.reduce((x, y) => x + y)));
+ expect(
+ wrapped.reduce((x, y) => x + y),
+ equals(original.reduce((x, y) => x + y)),
+ );
}
});
@@ -204,8 +214,10 @@
if (original.length != 1) {
expect(() => wrapped.singleWhere((_) => true), throwsStateError);
} else {
- expect(wrapped.singleWhere((_) => true),
- equals(original.singleWhere((_) => true)));
+ expect(
+ wrapped.singleWhere((_) => true),
+ equals(original.singleWhere((_) => true)),
+ );
}
expect(() => wrapped.singleWhere((_) => false), throwsStateError);
});
@@ -217,12 +229,18 @@
});
test('$name - skipWhile', () {
- expect(wrapped.skipWhile((x) => true),
- orderedEquals(original.skipWhile((x) => true)));
- expect(wrapped.skipWhile((x) => false),
- orderedEquals(original.skipWhile((x) => false)));
- expect(wrapped.skipWhile((x) => x != 42),
- orderedEquals(original.skipWhile((x) => x != 42)));
+ expect(
+ wrapped.skipWhile((x) => true),
+ orderedEquals(original.skipWhile((x) => true)),
+ );
+ expect(
+ wrapped.skipWhile((x) => false),
+ orderedEquals(original.skipWhile((x) => false)),
+ );
+ expect(
+ wrapped.skipWhile((x) => x != 42),
+ orderedEquals(original.skipWhile((x) => x != 42)),
+ );
});
test('$name - take', () {
@@ -232,18 +250,26 @@
});
test('$name - takeWhile', () {
- expect(wrapped.takeWhile((x) => true),
- orderedEquals(original.takeWhile((x) => true)));
- expect(wrapped.takeWhile((x) => false),
- orderedEquals(original.takeWhile((x) => false)));
- expect(wrapped.takeWhile((x) => x != 42),
- orderedEquals(original.takeWhile((x) => x != 42)));
+ expect(
+ wrapped.takeWhile((x) => true),
+ orderedEquals(original.takeWhile((x) => true)),
+ );
+ expect(
+ wrapped.takeWhile((x) => false),
+ orderedEquals(original.takeWhile((x) => false)),
+ );
+ expect(
+ wrapped.takeWhile((x) => x != 42),
+ orderedEquals(original.takeWhile((x) => x != 42)),
+ );
});
test('$name - toList', () {
expect(wrapped.toList(), orderedEquals(original.toList()));
- expect(wrapped.toList(growable: false),
- orderedEquals(original.toList(growable: false)));
+ expect(
+ wrapped.toList(growable: false),
+ orderedEquals(original.toList(growable: false)),
+ );
});
test('$name - toSet', () {
@@ -252,11 +278,17 @@
test('$name - where', () {
expect(
- wrapped.where((x) => true), orderedEquals(original.where((x) => true)));
- expect(wrapped.where((x) => false),
- orderedEquals(original.where((x) => false)));
- expect(wrapped.where((x) => x != 42),
- orderedEquals(original.where((x) => x != 42)));
+ wrapped.where((x) => true),
+ orderedEquals(original.where((x) => true)),
+ );
+ expect(
+ wrapped.where((x) => false),
+ orderedEquals(original.where((x) => false)),
+ );
+ expect(
+ wrapped.where((x) => x != 42),
+ orderedEquals(original.where((x) => x != 42)),
+ );
});
}
@@ -295,10 +327,14 @@
test('$name - getRange', () {
var len = original.length;
expect(wrapped.getRange(0, len), equals(original.getRange(0, len)));
- expect(wrapped.getRange(len ~/ 2, len),
- equals(original.getRange(len ~/ 2, len)));
expect(
- wrapped.getRange(0, len ~/ 2), equals(original.getRange(0, len ~/ 2)));
+ wrapped.getRange(len ~/ 2, len),
+ equals(original.getRange(len ~/ 2, len)),
+ );
+ expect(
+ wrapped.getRange(0, len ~/ 2),
+ equals(original.getRange(0, len ~/ 2)),
+ );
});
test('$name - sublist', () {
@@ -338,7 +374,10 @@
testThrows('$name - setRange throws', () {
wrapped.setRange(
- 0, wrapped.length, Iterable.generate(wrapped.length, (i) => i));
+ 0,
+ wrapped.length,
+ Iterable.generate(wrapped.length, (i) => i),
+ );
});
testThrows('$name - setAll throws', () {
@@ -394,7 +433,10 @@
}
void testNoChangeLengthList(
- List<int> original, List<int> wrapped, String name) {
+ List<int> original,
+ List<int> wrapped,
+ String name,
+) {
var copy = List.of(original);
void testThrows(String name, void Function() thunk) {
@@ -472,7 +514,9 @@
expect(wrapped.intersection({}), isEmpty);
expect(wrapped.intersection(copy), unorderedEquals(original));
expect(
- wrapped.intersection({42}), Set.of(original.contains(42) ? [42] : []));
+ wrapped.intersection({42}),
+ Set.of(original.contains(42) ? [42] : []),
+ );
});
test('$name - union', () {
diff --git a/pkgs/collection/test/wrapper_test.dart b/pkgs/collection/test/wrapper_test.dart
index 65a693f..d08091e 100644
--- a/pkgs/collection/test/wrapper_test.dart
+++ b/pkgs/collection/test/wrapper_test.dart
@@ -76,6 +76,7 @@
testInvocations(_expected, toStringInvocation);
return '';
}
+
// Could also handle runtimeType, hashCode and == the same way as
// toString, but we are not testing them since collections generally
// don't override those and so the wrappers don't forward those.
@@ -182,9 +183,10 @@
// expectation (which doesn't have the interface implemented or
// its default values).
(expect..firstWhere(boolFunc, orElse: null)).equals.firstWhere(boolFunc);
- (expect..firstWhere(boolFunc, orElse: func0))
- .equals
- .firstWhere(boolFunc, orElse: func0);
+ (expect..firstWhere(boolFunc, orElse: func0)).equals.firstWhere(
+ boolFunc,
+ orElse: func0,
+ );
(expect..fold(42, foldFunc)).equals.fold(42, foldFunc);
(expect..forEach(boolFunc)).equals.forEach(boolFunc);
(expect..isEmpty).equals.isEmpty;
@@ -194,9 +196,10 @@
(expect..join('X')).equals.join('X');
(expect..last).equals.last;
(expect..lastWhere(boolFunc, orElse: null)).equals.lastWhere(boolFunc);
- (expect..lastWhere(boolFunc, orElse: func0))
- .equals
- .lastWhere(boolFunc, orElse: func0);
+ (expect..lastWhere(boolFunc, orElse: func0)).equals.lastWhere(
+ boolFunc,
+ orElse: func0,
+ );
(expect..length).equals.length;
(expect..map(func1)).equals.map(func1);
(expect..reduce(func2)).equals.reduce(func2);
@@ -238,9 +241,14 @@
(expect..reversed).equals.reversed;
(expect..setAll(4, [val])).equals.setAll(4, [val]);
(expect..setRange(4, 5, [val], 0)).equals.setRange(4, 5, [val]);
- (expect..setRange(4, 5, [val, val], 1))
- .equals
- .setRange(4, 5, [val, val], 1);
+ (expect..setRange(4, 5, [val, val], 1)).equals.setRange(
+ 4,
+ 5,
+ [
+ val,
+ val,
+ ],
+ 1);
(expect..sort()).equals.sort();
(expect..sort(compareFunc)).equals.sort(compareFunc);
(expect..sublist(4, null)).equals.sublist(4);
@@ -329,9 +337,12 @@
});
test('.expand', () {
- expect(set.expand((element) {
- return [element.substring(0, 1), element.substring(1)];
- }), equals(['f', 'oo', 'b', 'ar']));
+ expect(
+ set.expand((element) {
+ return [element.substring(0, 1), element.substring(1)];
+ }),
+ equals(['f', 'oo', 'b', 'ar']),
+ );
});
test('.first', () {
@@ -340,19 +351,25 @@
test('.firstWhere', () {
expect(set.firstWhere((element) => true), equals('foo'));
- expect(set.firstWhere((element) => element.startsWith('b')),
- equals('bar'));
- expect(() => set.firstWhere((element) => element is int),
- throwsStateError);
- expect(set.firstWhere((element) => element is int, orElse: () => 'baz'),
- equals('baz'));
+ expect(
+ set.firstWhere((element) => element.startsWith('b')),
+ equals('bar'),
+ );
+ expect(
+ () => set.firstWhere((element) => element is int),
+ throwsStateError,
+ );
+ expect(
+ set.firstWhere((element) => element is int, orElse: () => 'baz'),
+ equals('baz'),
+ );
});
test('.fold', () {
expect(
- set.fold(
- 'start', (dynamic previous, element) => previous + element),
- equals('startfoobar'));
+ set.fold('start', (dynamic previous, element) => previous + element),
+ equals('startfoobar'),
+ );
});
test('.forEach', () {
@@ -380,26 +397,38 @@
test('.lastWhere', () {
expect(set.lastWhere((element) => true), equals('bar'));
expect(
- set.lastWhere((element) => element.startsWith('f')), equals('foo'));
+ set.lastWhere((element) => element.startsWith('f')),
+ equals('foo'),
+ );
expect(
- () => set.lastWhere((element) => element is int), throwsStateError);
- expect(set.lastWhere((element) => element is int, orElse: () => 'baz'),
- equals('baz'));
+ () => set.lastWhere((element) => element is int),
+ throwsStateError,
+ );
+ expect(
+ set.lastWhere((element) => element is int, orElse: () => 'baz'),
+ equals('baz'),
+ );
});
test('.map', () {
expect(
- set.map((element) => element.substring(1)), equals(['oo', 'ar']));
+ set.map((element) => element.substring(1)),
+ equals(['oo', 'ar']),
+ );
});
test('.reduce', () {
- expect(set.reduce((previous, element) => previous + element),
- equals('foobar'));
+ expect(
+ set.reduce((previous, element) => previous + element),
+ equals('foobar'),
+ );
});
test('.singleWhere', () {
- expect(() => set.singleWhere((element) => element == 'baz'),
- throwsStateError);
+ expect(
+ () => set.singleWhere((element) => element == 'baz'),
+ throwsStateError,
+ );
expect(set.singleWhere((element) => element == 'foo'), 'foo');
expect(() => set.singleWhere((element) => true), throwsStateError);
});
@@ -411,10 +440,14 @@
});
test('.skipWhile', () {
- expect(set.skipWhile((element) => element.startsWith('f')),
- equals(['bar']));
- expect(set.skipWhile((element) => element.startsWith('z')),
- equals(['foo', 'bar']));
+ expect(
+ set.skipWhile((element) => element.startsWith('f')),
+ equals(['bar']),
+ );
+ expect(
+ set.skipWhile((element) => element.startsWith('z')),
+ equals(['foo', 'bar']),
+ );
expect(set.skipWhile((element) => true), equals([]));
});
@@ -425,16 +458,20 @@
});
test('.takeWhile', () {
- expect(set.takeWhile((element) => element.startsWith('f')),
- equals(['foo']));
+ expect(
+ set.takeWhile((element) => element.startsWith('f')),
+ equals(['foo']),
+ );
expect(set.takeWhile((element) => element.startsWith('z')), equals([]));
expect(set.takeWhile((element) => true), equals(['foo', 'bar']));
});
test('.toList', () {
expect(set.toList(), equals(['foo', 'bar']));
- expect(() => set.toList(growable: false).add('baz'),
- throwsUnsupportedError);
+ expect(
+ () => set.toList(growable: false).add('baz'),
+ throwsUnsupportedError,
+ );
expect(set.toList()..add('baz'), equals(['foo', 'bar', 'baz']));
});
@@ -444,7 +481,9 @@
test('.where', () {
expect(
- set.where((element) => element.startsWith('f')), equals(['foo']));
+ set.where((element) => element.startsWith('f')),
+ equals(['foo']),
+ );
expect(set.where((element) => element.startsWith('z')), equals([]));
expect(set.whereType<String>(), equals(['foo', 'bar']));
});
@@ -563,8 +602,10 @@
setUp(() {
map = <String, String>{};
- set =
- MapValueSet<String, String>(map, (string) => string.substring(0, 1));
+ set = MapValueSet<String, String>(
+ map,
+ (string) => string.substring(0, 1),
+ );
});
testTwoElementSet(() {
@@ -672,11 +713,14 @@
test('.retainAll respects an unusual notion of equality', () {
map = HashMap<String, String>(
- equals: (value1, value2) =>
- value1.toLowerCase() == value2.toLowerCase(),
- hashCode: (value) => value.toLowerCase().hashCode);
- set =
- MapValueSet<String, String>(map, (string) => string.substring(0, 1));
+ equals: (value1, value2) =>
+ value1.toLowerCase() == value2.toLowerCase(),
+ hashCode: (value) => value.toLowerCase().hashCode,
+ );
+ set = MapValueSet<String, String>(
+ map,
+ (string) => string.substring(0, 1),
+ );
map['f'] = 'foo';
map['B'] = 'bar';
diff --git a/pkgs/convert/CHANGELOG.md b/pkgs/convert/CHANGELOG.md
index 8fc7ff5..96d0fe4 100644
--- a/pkgs/convert/CHANGELOG.md
+++ b/pkgs/convert/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 3.1.3-wip
+
+- Run `dart format` with the new style.
+
## 3.1.2
- Require Dart 3.4
diff --git a/pkgs/convert/lib/src/codepage.dart b/pkgs/convert/lib/src/codepage.dart
index c298ff5..86360e0 100644
--- a/pkgs/convert/lib/src/codepage.dart
+++ b/pkgs/convert/lib/src/codepage.dart
@@ -6,60 +6,88 @@
import 'dart:typed_data';
/// The ISO-8859-2/Latin-2 (Eastern European) code page.
-final CodePage latin2 =
- CodePage._bmp('latin-2', '$_ascii$_noControls$_top8859_2');
+final CodePage latin2 = CodePage._bmp(
+ 'latin-2',
+ '$_ascii$_noControls$_top8859_2',
+);
/// The ISO-8859-3/Latin-3 (South European) code page.
-final CodePage latin3 =
- CodePage._bmp('latin-3', '$_ascii$_noControls$_top8859_3');
+final CodePage latin3 = CodePage._bmp(
+ 'latin-3',
+ '$_ascii$_noControls$_top8859_3',
+);
/// The ISO-8859-4/Latin-4 (North European) code page.
-final CodePage latin4 =
- CodePage._bmp('latin-4', '$_ascii$_noControls$_top8859_4');
+final CodePage latin4 = CodePage._bmp(
+ 'latin-4',
+ '$_ascii$_noControls$_top8859_4',
+);
/// The ISO-8859-5/Latin-Cyrillic code page.
-final CodePage latinCyrillic =
- CodePage._bmp('cyrillic', '$_ascii$_noControls$_top8859_5');
+final CodePage latinCyrillic = CodePage._bmp(
+ 'cyrillic',
+ '$_ascii$_noControls$_top8859_5',
+);
/// The ISO-8859-6/Latin-Arabic code page.
-final CodePage latinArabic =
- CodePage._bmp('arabic', '$_ascii$_noControls$_top8859_6');
+final CodePage latinArabic = CodePage._bmp(
+ 'arabic',
+ '$_ascii$_noControls$_top8859_6',
+);
/// The ISO-8859-7/Latin-Greek code page.
-final CodePage latinGreek =
- CodePage._bmp('greek', '$_ascii$_noControls$_top8859_7');
+final CodePage latinGreek = CodePage._bmp(
+ 'greek',
+ '$_ascii$_noControls$_top8859_7',
+);
/// The ISO-8859-7/Latin-Hebrew code page.
-final CodePage latinHebrew =
- CodePage._bmp('hebrew', '$_ascii$_noControls$_top8859_8');
+final CodePage latinHebrew = CodePage._bmp(
+ 'hebrew',
+ '$_ascii$_noControls$_top8859_8',
+);
/// The ISO-8859-9/Latin-5 (Turkish) code page.
-final CodePage latin5 =
- CodePage._bmp('latin-5', '$_ascii$_noControls$_top8859_9');
+final CodePage latin5 = CodePage._bmp(
+ 'latin-5',
+ '$_ascii$_noControls$_top8859_9',
+);
/// The ISO-8859-10/Latin-6 (Nordic) code page.
-final CodePage latin6 =
- CodePage._bmp('latin-6', '$_ascii$_noControls$_top8859_10');
+final CodePage latin6 = CodePage._bmp(
+ 'latin-6',
+ '$_ascii$_noControls$_top8859_10',
+);
/// The ISO-8859-11/Latin-Thai code page.
-final CodePage latinThai =
- CodePage._bmp('tis620', '$_ascii$_noControls$_top8859_11');
+final CodePage latinThai = CodePage._bmp(
+ 'tis620',
+ '$_ascii$_noControls$_top8859_11',
+);
/// The ISO-8859-13/Latin-6 (Baltic Rim) code page.
-final CodePage latin7 =
- CodePage._bmp('latin-7', '$_ascii$_noControls$_top8859_13');
+final CodePage latin7 = CodePage._bmp(
+ 'latin-7',
+ '$_ascii$_noControls$_top8859_13',
+);
/// The ISO-8859-14/Latin-8 (Celtic) code page.
-final CodePage latin8 =
- CodePage._bmp('latin-8', '$_ascii$_noControls$_top8859_14');
+final CodePage latin8 = CodePage._bmp(
+ 'latin-8',
+ '$_ascii$_noControls$_top8859_14',
+);
/// The ISO-8859-15/Latin-9 (Western European revised) code page.
-final CodePage latin9 =
- CodePage._bmp('latin-9', '$_ascii$_noControls$_top8859_15');
+final CodePage latin9 = CodePage._bmp(
+ 'latin-9',
+ '$_ascii$_noControls$_top8859_15',
+);
/// The ISO-8859-16/Latin-10 (South Eastern European) code page.
-final CodePage latin10 =
- CodePage._bmp('latin-10', '$_ascii$_noControls$_top8859_16');
+final CodePage latin10 = CodePage._bmp(
+ 'latin-10',
+ '$_ascii$_noControls$_top8859_16',
+);
/// Characters in ISO-8859-2 above the ASCII and top control characters.
const _top8859_2 = '\xa0Ą˘Ł¤ĽŚ§¨ŠŞŤŹ\xadŽŻ°ą˛ł´ľśˇ¸šşťź˝žż'
@@ -261,14 +289,20 @@
for (var char in characters.runes) {
if (i >= 256) {
throw ArgumentError.value(
- characters, 'characters', 'Must contain 256 characters');
+ characters,
+ 'characters',
+ 'Must contain 256 characters',
+ );
}
result[i++] = char;
allChars |= char;
}
if (i < 256) {
throw ArgumentError.value(
- characters, 'characters', 'Must contain 256 characters');
+ characters,
+ 'characters',
+ 'Must contain 256 characters',
+ );
}
if (allChars <= 0xFFFF) {
// It's in the BMP.
@@ -312,13 +346,19 @@
for (var char in characters.runes) {
if (i >= 256) {
throw ArgumentError.value(
- characters, 'characters', 'Must contain 256 characters');
+ characters,
+ 'characters',
+ 'Must contain 256 characters',
+ );
}
result[i++] = char;
}
if (i < 256) {
throw ArgumentError.value(
- characters, 'characters', 'Must contain 256 characters');
+ characters,
+ 'characters',
+ 'Must contain 256 characters',
+ );
}
return result;
}
@@ -356,8 +396,11 @@
final String _characters;
_BmpCodePageDecoder(String characters) : _characters = characters {
if (characters.length != 256) {
- throw ArgumentError.value(characters, 'characters',
- 'Must contain 256 characters. Was ${characters.length}');
+ throw ArgumentError.value(
+ characters,
+ 'characters',
+ 'Must contain 256 characters. Was ${characters.length}',
+ );
}
}
@@ -440,7 +483,11 @@
Uint8List convert(String input, {int? invalidCharacter}) {
if (invalidCharacter != null) {
RangeError.checkValueInInterval(
- invalidCharacter, 0, 255, 'invalidCharacter');
+ invalidCharacter,
+ 0,
+ 255,
+ 'invalidCharacter',
+ );
}
var count = input.length;
var result = Uint8List(count);
@@ -463,7 +510,10 @@
}
byte = invalidCharacter ??
(throw FormatException(
- 'Not a character in this code page', input, offset));
+ 'Not a character in this code page',
+ input,
+ offset,
+ ));
}
result[j++] = byte;
}
diff --git a/pkgs/convert/lib/src/fixed_datetime_formatter.dart b/pkgs/convert/lib/src/fixed_datetime_formatter.dart
index fc0a58a..00b4838 100644
--- a/pkgs/convert/lib/src/fixed_datetime_formatter.dart
+++ b/pkgs/convert/lib/src/fixed_datetime_formatter.dart
@@ -87,10 +87,11 @@
var hasSeenBefore = _blocks.formatCharacters.indexOf(formatCharacter);
if (hasSeenBefore > -1) {
throw FormatException(
- "Pattern contains more than one '$formatCharacter' block.\n"
- 'Previous occurrence at index ${_blocks.starts[hasSeenBefore]}',
- pattern,
- i);
+ "Pattern contains more than one '$formatCharacter' block.\n"
+ 'Previous occurrence at index ${_blocks.starts[hasSeenBefore]}',
+ pattern,
+ i,
+ );
} else {
start = i;
currentCharacter = formatCharacter;
@@ -199,12 +200,14 @@
break;
default:
throw AssertionError(
- 'Unreachable, length is restricted to 6 in the constructor');
+ 'Unreachable, length is restricted to 6 in the constructor',
+ );
}
break;
default:
throw AssertionError(
- 'Unreachable, the key is checked in the constructor');
+ 'Unreachable, the key is checked in the constructor',
+ );
}
return value.toString().padLeft(length, '0');
}
@@ -229,11 +232,7 @@
DateTime? tryDecode(String formattedDateTime) =>
_decode(formattedDateTime, isUtc, false);
- DateTime? _decode(
- String formattedDateTime,
- bool isUtc,
- bool throwOnError,
- ) {
+ DateTime? _decode(String formattedDateTime, bool isUtc, bool throwOnError) {
var year = 0;
var month = 1;
var day = 1;
@@ -295,16 +294,7 @@
microsecond,
);
} else {
- return DateTime(
- year,
- month,
- day,
- hour,
- minute,
- second,
- 0,
- microsecond,
- );
+ return DateTime(year, month, day, hour, minute, second, 0, microsecond);
}
}
@@ -319,11 +309,10 @@
_blocks.ends[index],
);
if (parsed == null && throwOnError) {
+ var block = formattedDateTime.substring(
+ _blocks.starts[index], _blocks.ends[index]);
throw FormatException(
- 'Expected digits at ${formattedDateTime.substring(
- _blocks.starts[index],
- _blocks.ends[index],
- )}',
+ 'Expected digits at $block',
formattedDateTime,
_blocks.starts[index],
);
diff --git a/pkgs/convert/lib/src/hex/decoder.dart b/pkgs/convert/lib/src/hex/decoder.dart
index 3696d4d..8b352f4 100644
--- a/pkgs/convert/lib/src/hex/decoder.dart
+++ b/pkgs/convert/lib/src/hex/decoder.dart
@@ -93,7 +93,10 @@
void _close([String? string, int? index]) {
if (_lastDigit != null) {
throw FormatException(
- 'Input ended with incomplete encoded byte.', string, index);
+ 'Input ended with incomplete encoded byte.',
+ string,
+ index,
+ );
}
_sink.close();
@@ -153,7 +156,10 @@
void _close([List<int>? chunk, int? index]) {
if (_lastDigit != null) {
throw FormatException(
- 'Input ended with incomplete encoded byte.', chunk, index);
+ 'Input ended with incomplete encoded byte.',
+ chunk,
+ index,
+ );
}
_sink.close();
@@ -167,8 +173,13 @@
///
/// If there's a leftover digit at the end of the decoding, this returns that
/// digit. Otherwise it returns `null`.
-int? _decode(List<int> codeUnits, int sourceStart, int sourceEnd,
- List<int> destination, int destinationStart) {
+int? _decode(
+ List<int> codeUnits,
+ int sourceStart,
+ int sourceEnd,
+ List<int> destination,
+ int destinationStart,
+) {
var destinationIndex = destinationStart;
for (var i = sourceStart; i < sourceEnd - 1; i += 2) {
var firstDigit = digitForCodeUnit(codeUnits, i);
diff --git a/pkgs/convert/lib/src/hex/encoder.dart b/pkgs/convert/lib/src/hex/encoder.dart
index 36d6c22..54aad13 100644
--- a/pkgs/convert/lib/src/hex/encoder.dart
+++ b/pkgs/convert/lib/src/hex/encoder.dart
@@ -79,9 +79,10 @@
var byte = bytes[i];
if (byte >= 0 && byte <= 0xff) continue;
throw FormatException(
- "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.",
- bytes,
- i);
+ "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.",
+ bytes,
+ i,
+ );
}
throw StateError('unreachable');
diff --git a/pkgs/convert/lib/src/percent/decoder.dart b/pkgs/convert/lib/src/percent/decoder.dart
index ef9c8a8..1e6057f 100644
--- a/pkgs/convert/lib/src/percent/decoder.dart
+++ b/pkgs/convert/lib/src/percent/decoder.dart
@@ -33,7 +33,10 @@
if (lastDigit != null) {
throw FormatException(
- 'Input ended with incomplete encoded byte.', input, input.length);
+ 'Input ended with incomplete encoded byte.',
+ input,
+ input.length,
+ );
}
return buffer.buffer.asUint8List(0, buffer.length);
@@ -104,7 +107,10 @@
void _close([String? string, int? index]) {
if (_lastDigit != null) {
throw FormatException(
- 'Input ended with incomplete encoded byte.', string, index);
+ 'Input ended with incomplete encoded byte.',
+ string,
+ index,
+ );
}
_sink.close();
@@ -169,7 +175,10 @@
void _close([List<int>? chunk, int? index]) {
if (_lastDigit != null) {
throw FormatException(
- 'Input ended with incomplete encoded byte.', chunk, index);
+ 'Input ended with incomplete encoded byte.',
+ chunk,
+ index,
+ );
}
_sink.close();
@@ -235,16 +244,21 @@
}
void _checkForInvalidCodeUnit(
- int codeUnitOr, List<int> codeUnits, int start, int end) {
+ int codeUnitOr,
+ List<int> codeUnits,
+ int start,
+ int end,
+) {
if (codeUnitOr >= 0 && codeUnitOr <= 0x7f) return;
for (var i = start; i < end; i++) {
var codeUnit = codeUnits[i];
if (codeUnit >= 0 && codeUnit <= 0x7f) continue;
throw FormatException(
- 'Non-ASCII code unit '
- "U+${codeUnit.toRadixString(16).padLeft(4, '0')}",
- codeUnits,
- i);
+ 'Non-ASCII code unit '
+ "U+${codeUnit.toRadixString(16).padLeft(4, '0')}",
+ codeUnits,
+ i,
+ );
}
}
diff --git a/pkgs/convert/lib/src/percent/encoder.dart b/pkgs/convert/lib/src/percent/encoder.dart
index b087b7a..99a6791 100644
--- a/pkgs/convert/lib/src/percent/encoder.dart
+++ b/pkgs/convert/lib/src/percent/encoder.dart
@@ -96,9 +96,10 @@
var byte = bytes[i];
if (byte >= 0 && byte <= 0xff) continue;
throw FormatException(
- "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.",
- bytes,
- i);
+ "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.",
+ bytes,
+ i,
+ );
}
throw StateError('unreachable');
diff --git a/pkgs/convert/lib/src/utils.dart b/pkgs/convert/lib/src/utils.dart
index cfcc127..3a0753c 100644
--- a/pkgs/convert/lib/src/utils.dart
+++ b/pkgs/convert/lib/src/utils.dart
@@ -30,8 +30,9 @@
}
throw FormatException(
- 'Invalid hexadecimal code unit '
- "U+${codeUnit.toRadixString(16).padLeft(4, '0')}.",
- codeUnits,
- index);
+ 'Invalid hexadecimal code unit '
+ "U+${codeUnit.toRadixString(16).padLeft(4, '0')}.",
+ codeUnits,
+ index,
+ );
}
diff --git a/pkgs/convert/pubspec.yaml b/pkgs/convert/pubspec.yaml
index 25c46ce..fa9edcd 100644
--- a/pkgs/convert/pubspec.yaml
+++ b/pkgs/convert/pubspec.yaml
@@ -1,5 +1,5 @@
name: convert
-version: 3.1.2
+version: 3.1.3-wip
description: >-
Utilities for converting between data representations.
Provides a number of Sink, Codec, Decoder, and Encoder types.
diff --git a/pkgs/convert/test/codepage_test.dart b/pkgs/convert/test/codepage_test.dart
index cca75e7..28557e8 100644
--- a/pkgs/convert/test/codepage_test.dart
+++ b/pkgs/convert/test/codepage_test.dart
@@ -25,7 +25,7 @@
latinGreek,
latinHebrew,
latinThai,
- latinArabic
+ latinArabic,
]) {
group('${cp.name} codepage', () {
test('ascii compatible', () {
@@ -52,14 +52,17 @@
test('decode invalid characters allowed', () {
// Decode works like operator[].
- expect(cp.decode(bytes, allowInvalid: true),
- String.fromCharCodes([for (var i = 0; i < 256; i++) cp[i]]));
+ expect(
+ cp.decode(bytes, allowInvalid: true),
+ String.fromCharCodes([for (var i = 0; i < 256; i++) cp[i]]),
+ );
});
test('chunked conversion', () {
late final String decodedString;
final outputSink = StringConversionSink.withCallback(
- (accumulated) => decodedString = accumulated);
+ (accumulated) => decodedString = accumulated,
+ );
final inputSink = cp.decoder.startChunkedConversion(outputSink);
final expected = StringBuffer();
@@ -123,7 +126,8 @@
test('chunked conversion', () {
late final String decodedString;
final outputSink = StringConversionSink.withCallback(
- (accumulated) => decodedString = accumulated);
+ (accumulated) => decodedString = accumulated,
+ );
final inputSink = cp.decoder.startChunkedConversion(outputSink);
inputSink
@@ -137,7 +141,8 @@
test('chunked conversion - byte conversion sink', () {
late final String decodedString;
final outputSink = StringConversionSink.withCallback(
- (accumulated) => decodedString = accumulated);
+ (accumulated) => decodedString = accumulated,
+ );
final bytes = [1, 0, 3, 2, 0, 5, 4];
final inputSink = cp.decoder.startChunkedConversion(outputSink);
diff --git a/pkgs/convert/test/fixed_datetime_formatter_test.dart b/pkgs/convert/test/fixed_datetime_formatter_test.dart
index 30e7ca9..43fea6e 100644
--- a/pkgs/convert/test/fixed_datetime_formatter_test.dart
+++ b/pkgs/convert/test/fixed_datetime_formatter_test.dart
@@ -9,7 +9,8 @@
var noFractionalSeconds = DateTime.utc(0);
var skipWeb = <String, Skip>{
'js': const Skip(
- 'Web does not support microseconds (see https://github.com/dart-lang/sdk/issues/44876)')
+ 'Web does not support microseconds (see https://github.com/dart-lang/sdk/issues/44876)',
+ ),
};
// Testing `decode`.
test('Parse only year', () {
@@ -40,13 +41,15 @@
expect(time, DateTime.utc(1996, 4, 25));
});
test('Parse year, century, month, day, hour, minute, second', () {
- var time = FixedDateTimeFormatter('CCYY MM-DD hh:mm:ss')
- .decode('1996 04-25 05:03:22');
+ var time = FixedDateTimeFormatter(
+ 'CCYY MM-DD hh:mm:ss',
+ ).decode('1996 04-25 05:03:22');
expect(time, DateTime.utc(1996, 4, 25, 5, 3, 22));
});
test('Parse YYYYMMDDhhmmssSSS', () {
- var time =
- FixedDateTimeFormatter('YYYYMMDDhhmmssSSS').decode('19960425050322533');
+ var time = FixedDateTimeFormatter(
+ 'YYYYMMDDhhmmssSSS',
+ ).decode('19960425050322533');
expect(time, DateTime.utc(1996, 4, 25, 5, 3, 22, 533));
});
test('Parse S 1/10 of a second', () {
@@ -72,32 +75,22 @@
test('Parse SSSSSS a millisecond and a microsecond', () {
var time = FixedDateTimeFormatter('SSSSSS').decode('001001');
expect(
- time,
- noFractionalSeconds.add(const Duration(
- milliseconds: 1,
- microseconds: 1,
- )));
+ time,
+ noFractionalSeconds.add(const Duration(milliseconds: 1, microseconds: 1)),
+ );
}, onPlatform: skipWeb);
test('Parse ssSSSSSS a second and a microsecond', () {
var time = FixedDateTimeFormatter('ssSSSSSS').decode('01000001');
expect(
- time,
- noFractionalSeconds.add(const Duration(
- seconds: 1,
- microseconds: 1,
- )));
+ time,
+ noFractionalSeconds.add(const Duration(seconds: 1, microseconds: 1)),
+ );
}, onPlatform: skipWeb);
test('7 S throws', () {
- expect(
- () => FixedDateTimeFormatter('S' * 7),
- throwsFormatException,
- );
+ expect(() => FixedDateTimeFormatter('S' * 7), throwsFormatException);
});
test('10 Y throws', () {
- expect(
- () => FixedDateTimeFormatter('Y' * 10),
- throwsFormatException,
- );
+ expect(() => FixedDateTimeFormatter('Y' * 10), throwsFormatException);
});
test('Parse hex year throws', () {
expect(
@@ -139,18 +132,21 @@
expect(str, 'X1996-04X');
});
test('Format S 1/10 of a second', () {
- var str = FixedDateTimeFormatter('S')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
+ var str = FixedDateTimeFormatter(
+ 'S',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
expect(str, '1');
});
test('Format SS 1/100 of a second', () {
- var str = FixedDateTimeFormatter('SS')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
+ var str = FixedDateTimeFormatter(
+ 'SS',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
expect(str, '01');
});
test('Format SSS 1/100 of a second', () {
- var str = FixedDateTimeFormatter('SSS')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
+ var str = FixedDateTimeFormatter(
+ 'SSS',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
expect(str, '010');
});
test('Format SSSS no fractions', () {
@@ -162,56 +158,59 @@
expect(str, '000000');
});
test('Format SSSS 1/10 of a second', () {
- var str = FixedDateTimeFormatter('SSSS')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
+ var str = FixedDateTimeFormatter(
+ 'SSSS',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
expect(str, '1000');
});
test('Format SSSS 1/100 of a second', () {
- var str = FixedDateTimeFormatter('SSSS')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
+ var str = FixedDateTimeFormatter(
+ 'SSSS',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 10)));
expect(str, '0100');
});
test('Format SSSS a millisecond', () {
- var str = FixedDateTimeFormatter('SSSS')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 1)));
+ var str = FixedDateTimeFormatter(
+ 'SSSS',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 1)));
expect(str, '0010');
});
test('Format SSSSSS a microsecond', () {
- var str = FixedDateTimeFormatter('SSSSSS')
- .encode(DateTime.utc(0, 1, 1, 0, 0, 0, 0, 1));
+ var str = FixedDateTimeFormatter(
+ 'SSSSSS',
+ ).encode(DateTime.utc(0, 1, 1, 0, 0, 0, 0, 1));
expect(str, '000001');
}, onPlatform: skipWeb);
test('Format SSSSSS a millisecond and a microsecond', () {
- var dateTime = noFractionalSeconds.add(const Duration(
- milliseconds: 1,
- microseconds: 1,
- ));
+ var dateTime = noFractionalSeconds.add(
+ const Duration(milliseconds: 1, microseconds: 1),
+ );
var str = FixedDateTimeFormatter('SSSSSS').encode(dateTime);
expect(str, '001001');
}, onPlatform: skipWeb);
test('Format SSSSSS0 a microsecond', () {
- var str = FixedDateTimeFormatter('SSSSSS0')
- .encode(noFractionalSeconds.add(const Duration(microseconds: 1)));
+ var str = FixedDateTimeFormatter(
+ 'SSSSSS0',
+ ).encode(noFractionalSeconds.add(const Duration(microseconds: 1)));
expect(str, '0000010');
}, onPlatform: skipWeb);
test('Format SSSSSS0 1/10 of a second', () {
- var str = FixedDateTimeFormatter('SSSSSS0')
- .encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
+ var str = FixedDateTimeFormatter(
+ 'SSSSSS0',
+ ).encode(noFractionalSeconds.add(const Duration(milliseconds: 100)));
expect(str, '1000000');
});
test('Parse ssSSSSSS a second and a microsecond', () {
- var dateTime = noFractionalSeconds.add(const Duration(
- seconds: 1,
- microseconds: 1,
- ));
+ var dateTime = noFractionalSeconds.add(
+ const Duration(seconds: 1, microseconds: 1),
+ );
var str = FixedDateTimeFormatter('ssSSSSSS').encode(dateTime);
expect(str, '01000001');
}, onPlatform: skipWeb);
test('Parse ssSSSSSS0 a second and a microsecond', () {
- var dateTime = noFractionalSeconds.add(const Duration(
- seconds: 1,
- microseconds: 1,
- ));
+ var dateTime = noFractionalSeconds.add(
+ const Duration(seconds: 1, microseconds: 1),
+ );
var str = FixedDateTimeFormatter('ssSSSSSS0').encode(dateTime);
expect(str, '010000010');
}, onPlatform: skipWeb);
diff --git a/pkgs/convert/test/hex_test.dart b/pkgs/convert/test/hex_test.dart
index abd940f..0b90975 100644
--- a/pkgs/convert/test/hex_test.dart
+++ b/pkgs/convert/test/hex_test.dart
@@ -49,8 +49,9 @@
test('rejects non-bytes', () {
expect(() => hex.encode([0x100]), throwsFormatException);
- var sink =
- hex.encoder.startChunkedConversion(StreamController(sync: true));
+ var sink = hex.encoder.startChunkedConversion(
+ StreamController(sync: true),
+ );
expect(() => sink.add([0x100]), throwsFormatException);
});
});
@@ -63,20 +64,21 @@
test('supports uppercase letters', () {
expect(
- hex.decode('0123456789ABCDEFabcdef'),
- equals([
- 0x01,
- 0x23,
- 0x45,
- 0x67,
- 0x89,
- 0xab,
- 0xcd,
- 0xef,
- 0xab,
- 0xcd,
- 0xef
- ]));
+ hex.decode('0123456789ABCDEFabcdef'),
+ equals([
+ 0x01,
+ 0x23,
+ 0x45,
+ 0x67,
+ 0x89,
+ 0xab,
+ 0xcd,
+ 0xef,
+ 0xab,
+ 0xcd,
+ 0xef,
+ ]),
+ );
});
group('with chunked conversion', () {
@@ -92,54 +94,60 @@
test('converts hex to byte arrays', () {
sink.add('1ab23cd4');
expect(
- results,
- equals([
- [0x1a, 0xb2, 0x3c, 0xd4]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2, 0x3c, 0xd4],
+ ]),
+ );
sink.add('0001feff');
expect(
- results,
- equals([
- [0x1a, 0xb2, 0x3c, 0xd4],
- [0x00, 0x01, 0xfe, 0xff]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2, 0x3c, 0xd4],
+ [0x00, 0x01, 0xfe, 0xff],
+ ]),
+ );
});
test('supports trailing digits split across chunks', () {
sink.add('1ab23');
expect(
- results,
- equals([
- [0x1a, 0xb2]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ ]),
+ );
sink.add('cd');
expect(
- results,
- equals([
- [0x1a, 0xb2],
- [0x3c]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ [0x3c],
+ ]),
+ );
sink.add('40001');
expect(
- results,
- equals([
- [0x1a, 0xb2],
- [0x3c],
- [0xd4, 0x00, 0x01]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ [0x3c],
+ [0xd4, 0x00, 0x01],
+ ]),
+ );
sink.add('feff');
expect(
- results,
- equals([
- [0x1a, 0xb2],
- [0x3c],
- [0xd4, 0x00, 0x01],
- [0xfe, 0xff]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ [0x3c],
+ [0xd4, 0x00, 0x01],
+ [0xfe, 0xff],
+ ]),
+ );
});
test('supports empty strings', () {
@@ -154,41 +162,47 @@
sink.add('0');
expect(
- results,
- equals([
- <Never>[],
- [0x00]
- ]));
+ results,
+ equals([
+ <Never>[],
+ [0x00],
+ ]),
+ );
sink.add('');
expect(
- results,
- equals([
- <Never>[],
- [0x00]
- ]));
+ results,
+ equals([
+ <Never>[],
+ [0x00],
+ ]),
+ );
});
test('rejects odd length detected in close()', () {
sink.add('1ab23');
expect(
- results,
- equals([
- [0x1a, 0xb2]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ ]),
+ );
expect(() => sink.close(), throwsFormatException);
});
test('rejects odd length detected in addSlice()', () {
sink.addSlice('1ab23cd', 0, 5, false);
expect(
- results,
- equals([
- [0x1a, 0xb2]
- ]));
+ results,
+ equals([
+ [0x1a, 0xb2],
+ ]),
+ );
expect(
- () => sink.addSlice('1ab23cd', 5, 7, true), throwsFormatException);
+ () => sink.addSlice('1ab23cd', 5, 7, true),
+ throwsFormatException,
+ );
});
});
@@ -202,14 +216,15 @@
'`',
'\x00',
'\u0141',
- '\u{10041}'
+ '\u{10041}',
]) {
test('"$char"', () {
expect(() => hex.decode('a$char'), throwsFormatException);
expect(() => hex.decode('${char}a'), throwsFormatException);
- var sink =
- hex.decoder.startChunkedConversion(StreamController(sync: true));
+ var sink = hex.decoder.startChunkedConversion(
+ StreamController(sync: true),
+ );
expect(() => sink.add(char), throwsFormatException);
});
}
diff --git a/pkgs/convert/test/percent_test.dart b/pkgs/convert/test/percent_test.dart
index 4e0f605..6787b05 100644
--- a/pkgs/convert/test/percent_test.dart
+++ b/pkgs/convert/test/percent_test.dart
@@ -18,8 +18,10 @@
});
test('percent-encodes reserved ASCII characters', () {
- expect(percent.encode([...' `{@[,/^}\x7f\x00%'.codeUnits]),
- equals('%20%60%7B%40%5B%2C%2F%5E%7D%7F%00%25'));
+ expect(
+ percent.encode([...' `{@[,/^}\x7f\x00%'.codeUnits]),
+ equals('%20%60%7B%40%5B%2C%2F%5E%7D%7F%00%25'),
+ );
});
test('percent-encodes non-ASCII characters', () {
@@ -64,8 +66,9 @@
test('rejects non-bytes', () {
expect(() => percent.encode([0x100]), throwsFormatException);
- var sink =
- percent.encoder.startChunkedConversion(StreamController(sync: true));
+ var sink = percent.encoder.startChunkedConversion(
+ StreamController(sync: true),
+ );
expect(() => sink.add([0x100]), throwsFormatException);
});
});
@@ -73,7 +76,9 @@
group('decoder', () {
test('converts percent-encoded strings to byte arrays', () {
expect(
- percent.decode('a%2Bb%3D%801'), equals([...'a+b=\x801'.codeUnits]));
+ percent.decode('a%2Bb%3D%801'),
+ equals([...'a+b=\x801'.codeUnits]),
+ );
});
test('supports lowercase letters', () {
@@ -102,51 +107,57 @@
test('converts percent to byte arrays', () {
sink.add('a%2Bb%3D%801');
expect(
- results,
- equals([
- [...'a+b=\x801'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'a+b=\x801'.codeUnits],
+ ]),
+ );
sink.add('%00%01%FE%FF');
expect(
- results,
- equals([
- [...'a+b=\x801'.codeUnits],
- [0x00, 0x01, 0xfe, 0xff]
- ]));
+ results,
+ equals([
+ [...'a+b=\x801'.codeUnits],
+ [0x00, 0x01, 0xfe, 0xff],
+ ]),
+ );
});
test('supports trailing percents and digits split across chunks', () {
sink.add('ab%');
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
sink.add('2');
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
sink.add('0cd%2');
expect(
- results,
- equals([
- [...'ab'.codeUnits],
- [...' cd'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ [...' cd'.codeUnits],
+ ]),
+ );
sink.add('0');
expect(
- results,
- equals([
- [...'ab'.codeUnits],
- [...' cd'.codeUnits],
- [...' '.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ [...' cd'.codeUnits],
+ [...' '.codeUnits],
+ ]),
+ );
});
test('supports empty strings', () {
@@ -167,40 +178,44 @@
sink.add('0');
expect(
- results,
- equals([
- <Never>[],
- [0x20]
- ]));
+ results,
+ equals([
+ <Never>[],
+ [0x20],
+ ]),
+ );
});
test('rejects dangling % detected in close()', () {
sink.add('ab%');
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
expect(() => sink.close(), throwsFormatException);
});
test('rejects dangling digit detected in close()', () {
sink.add('ab%2');
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
expect(() => sink.close(), throwsFormatException);
});
test('rejects danging % detected in addSlice()', () {
sink.addSlice('ab%', 0, 3, false);
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
expect(() => sink.addSlice('ab%', 0, 3, true), throwsFormatException);
});
@@ -208,10 +223,11 @@
test('rejects danging digit detected in addSlice()', () {
sink.addSlice('ab%2', 0, 3, false);
expect(
- results,
- equals([
- [...'ab'.codeUnits]
- ]));
+ results,
+ equals([
+ [...'ab'.codeUnits],
+ ]),
+ );
expect(() => sink.addSlice('ab%2', 0, 3, true), throwsFormatException);
});
@@ -223,8 +239,9 @@
expect(() => percent.decode('a$char'), throwsFormatException);
expect(() => percent.decode('${char}a'), throwsFormatException);
- var sink = percent.decoder
- .startChunkedConversion(StreamController(sync: true));
+ var sink = percent.decoder.startChunkedConversion(
+ StreamController(sync: true),
+ );
expect(() => sink.add(char), throwsFormatException);
});
}
diff --git a/pkgs/crypto/CHANGELOG.md b/pkgs/crypto/CHANGELOG.md
index f971b68..4aee58d 100644
--- a/pkgs/crypto/CHANGELOG.md
+++ b/pkgs/crypto/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 3.0.7-wip
+
+- Run `dart format` with the new style.
+
## 3.0.6
* Move to `dart-lang/core` monorepo.
diff --git a/pkgs/crypto/lib/src/hash_sink.dart b/pkgs/crypto/lib/src/hash_sink.dart
index cd23823..fcd8aa9 100644
--- a/pkgs/crypto/lib/src/hash_sink.dart
+++ b/pkgs/crypto/lib/src/hash_sink.dart
@@ -58,9 +58,12 @@
///
/// [chunkSizeInWords] represents the size of the input chunks processed by
/// the algorithm, in terms of 32-bit words.
- HashSink(this._sink, int chunkSizeInWords,
- {Endian endian = Endian.big, int signatureBytes = 8})
- : _endian = endian,
+ HashSink(
+ this._sink,
+ int chunkSizeInWords, {
+ Endian endian = Endian.big,
+ int signatureBytes = 8,
+ }) : _endian = endian,
assert(signatureBytes >= 8),
_signatureBytes = signatureBytes,
_currentChunk = Uint32List(chunkSizeInWords);
@@ -114,7 +117,9 @@
// Copy words from the pending data buffer into the current chunk buffer.
for (var j = 0; j < _currentChunk.length; j++) {
_currentChunk[j] = pendingDataBytes.getUint32(
- i * _currentChunk.lengthInBytes + j * bytesPerWord, _endian);
+ i * _currentChunk.lengthInBytes + j * bytesPerWord,
+ _endian,
+ );
}
// Run the hash function on the current chunk.
@@ -123,7 +128,9 @@
// Remove all pending data up to the last clean chunk break.
_pendingData.removeRange(
- 0, pendingDataChunks * _currentChunk.lengthInBytes);
+ 0,
+ pendingDataChunks * _currentChunk.lengthInBytes,
+ );
}
/// Finalizes [_pendingData].
@@ -136,8 +143,10 @@
_pendingData.add(0x80);
final contentsLength = _lengthInBytes + 1 /* 0x80 */ + _signatureBytes;
- final finalizedLength =
- _roundUp(contentsLength, _currentChunk.lengthInBytes);
+ final finalizedLength = _roundUp(
+ contentsLength,
+ _currentChunk.lengthInBytes,
+ );
for (var i = 0; i < finalizedLength - contentsLength; i++) {
_pendingData.add(0);
@@ -145,7 +154,8 @@
if (_lengthInBytes > _maxMessageLengthInBytes) {
throw UnsupportedError(
- 'Hashing is unsupported for messages with more than 2^53 bits.');
+ 'Hashing is unsupported for messages with more than 2^53 bits.',
+ );
}
var lengthInBits = _lengthInBytes * bitsPerByte;
diff --git a/pkgs/crypto/lib/src/md5.dart b/pkgs/crypto/lib/src/md5.dart
index df30a3f..8139325 100644
--- a/pkgs/crypto/lib/src/md5.dart
+++ b/pkgs/crypto/lib/src/md5.dart
@@ -50,7 +50,7 @@
0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92,
0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
- 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
+ 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
];
/// Per-round shift amounts.
@@ -58,7 +58,7 @@
07, 12, 17, 22, 07, 12, 17, 22, 07, 12, 17, 22, 07, 12, 17, 22, 05, 09, 14, //
20, 05, 09, 14, 20, 05, 09, 14, 20, 05, 09, 14, 20, 04, 11, 16, 23, 04, 11,
16, 23, 04, 11, 16, 23, 04, 11, 16, 23, 06, 10, 15, 21, 06, 10, 15, 21, 06,
- 10, 15, 21, 06, 10, 15, 21
+ 10, 15, 21, 06, 10, 15, 21,
];
/// The concrete implementation of `MD5`.
@@ -107,9 +107,12 @@
d = c;
c = b;
b = add32(
- b,
- rotl32(add32(add32(a, e), add32(_noise[i], chunk[f])),
- _shiftAmounts[i]));
+ b,
+ rotl32(
+ add32(add32(a, e), add32(_noise[i], chunk[f])),
+ _shiftAmounts[i],
+ ),
+ );
a = temp;
}
diff --git a/pkgs/crypto/lib/src/sha1.dart b/pkgs/crypto/lib/src/sha1.dart
index 5fc13a0..e085cba 100644
--- a/pkgs/crypto/lib/src/sha1.dart
+++ b/pkgs/crypto/lib/src/sha1.dart
@@ -68,11 +68,12 @@
_extended[i] = chunk[i];
} else {
_extended[i] = rotl32(
- _extended[i - 3] ^
- _extended[i - 8] ^
- _extended[i - 14] ^
- _extended[i - 16],
- 1);
+ _extended[i - 3] ^
+ _extended[i - 8] ^
+ _extended[i - 14] ^
+ _extended[i - 16],
+ 1,
+ );
}
var newA = add32(add32(rotl32(a, 5), e), _extended[i]);
diff --git a/pkgs/crypto/lib/src/sha256.dart b/pkgs/crypto/lib/src/sha256.dart
index 36808d3..ca0c955 100644
--- a/pkgs/crypto/lib/src/sha256.dart
+++ b/pkgs/crypto/lib/src/sha256.dart
@@ -65,7 +65,7 @@
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
abstract class _Sha32BitSink extends HashSink {
@@ -99,8 +99,10 @@
_extended[i] = chunk[i];
}
for (var i = 16; i < 64; i++) {
- _extended[i] = add32(add32(_ssig1(_extended[i - 2]), _extended[i - 7]),
- add32(_ssig0(_extended[i - 15]), _extended[i - 16]));
+ _extended[i] = add32(
+ add32(_ssig1(_extended[i - 2]), _extended[i - 7]),
+ add32(_ssig0(_extended[i - 15]), _extended[i - 16]),
+ );
}
// Shuffle around the bits.
@@ -114,8 +116,10 @@
var h = _digest[7];
for (var i = 0; i < 64; i++) {
- var temp1 = add32(add32(h, _bsig1(e)),
- add32(_ch(e, f, g), add32(_noise[i], _extended[i])));
+ var temp1 = add32(
+ add32(h, _bsig1(e)),
+ add32(_ch(e, f, g), add32(_noise[i], _extended[i])),
+ );
var temp2 = add32(_bsig0(a), _maj(a, b, c));
h = g;
g = f;
@@ -151,17 +155,18 @@
// of the square roots of the first 8 prime numbers.
_Sha256Sink(Sink<Digest> sink)
: super(
- sink,
- Uint32List.fromList([
- 0x6a09e667,
- 0xbb67ae85,
- 0x3c6ef372,
- 0xa54ff53a,
- 0x510e527f,
- 0x9b05688c,
- 0x1f83d9ab,
- 0x5be0cd19,
- ]));
+ sink,
+ Uint32List.fromList([
+ 0x6a09e667,
+ 0xbb67ae85,
+ 0x3c6ef372,
+ 0xa54ff53a,
+ 0x510e527f,
+ 0x9b05688c,
+ 0x1f83d9ab,
+ 0x5be0cd19,
+ ]),
+ );
}
/// The concrete implementation of `Sha224`.
@@ -174,15 +179,16 @@
_Sha224Sink(Sink<Digest> sink)
: super(
- sink,
- Uint32List.fromList([
- 0xc1059ed8,
- 0x367cd507,
- 0x3070dd17,
- 0xf70e5939,
- 0xffc00b31,
- 0x68581511,
- 0x64f98fa7,
- 0xbefa4fa4,
- ]));
+ sink,
+ Uint32List.fromList([
+ 0xc1059ed8,
+ 0x367cd507,
+ 0x3070dd17,
+ 0xf70e5939,
+ 0xffc00b31,
+ 0x68581511,
+ 0x64f98fa7,
+ 0xbefa4fa4,
+ ]),
+ );
}
diff --git a/pkgs/crypto/lib/src/sha512_fastsinks.dart b/pkgs/crypto/lib/src/sha512_fastsinks.dart
index c2a0f97..b36f7ed 100644
--- a/pkgs/crypto/lib/src/sha512_fastsinks.dart
+++ b/pkgs/crypto/lib/src/sha512_fastsinks.dart
@@ -106,17 +106,18 @@
Sha384Sink(Sink<Digest> sink)
: super(
- sink,
- Uint64List.fromList([
- 0xcbbb9d5dc1059ed8,
- 0x629a292a367cd507,
- 0x9159015a3070dd17,
- 0x152fecd8f70e5939,
- 0x67332667ffc00b31,
- 0x8eb44a8768581511,
- 0xdb0c2e0d64f98fa7,
- 0x47b5481dbefa4fa4,
- ]));
+ sink,
+ Uint64List.fromList([
+ 0xcbbb9d5dc1059ed8,
+ 0x629a292a367cd507,
+ 0x9159015a3070dd17,
+ 0x152fecd8f70e5939,
+ 0x67332667ffc00b31,
+ 0x8eb44a8768581511,
+ 0xdb0c2e0d64f98fa7,
+ 0x47b5481dbefa4fa4,
+ ]),
+ );
}
/// The concrete implementation of `Sha512`.
@@ -155,18 +156,19 @@
Sha512224Sink(Sink<Digest> sink)
: super(
- sink,
- Uint64List.fromList([
- // FIPS 180-4, Section 5.3.6.1
- 0x8c3d37c819544da2,
- 0x73e1996689dcd4d6,
- 0x1dfab7ae32ff9c82,
- 0x679dd514582f9fcf,
- 0x0f6d2b697bd44da8,
- 0x77e36f7304c48942,
- 0x3f9d85a86a1d36c8,
- 0x1112e6ad91d692a1,
- ]));
+ sink,
+ Uint64List.fromList([
+ // FIPS 180-4, Section 5.3.6.1
+ 0x8c3d37c819544da2,
+ 0x73e1996689dcd4d6,
+ 0x1dfab7ae32ff9c82,
+ 0x679dd514582f9fcf,
+ 0x0f6d2b697bd44da8,
+ 0x77e36f7304c48942,
+ 0x3f9d85a86a1d36c8,
+ 0x1112e6ad91d692a1,
+ ]),
+ );
}
/// The concrete implementation of [Sha512/256].
@@ -179,18 +181,19 @@
Sha512256Sink(Sink<Digest> sink)
: super(
- sink,
- Uint64List.fromList([
- // FIPS 180-4, Section 5.3.6.2
- 0x22312194fc2bf72c,
- 0x9f555fa3c84c64c2,
- 0x2393b86b6f53b151,
- 0x963877195940eabd,
- 0x96283ee2a88effe3,
- 0xbe5e1e2553863992,
- 0x2b0199fc2c85b8aa,
- 0x0eb72ddc81c52ca2,
- ]));
+ sink,
+ Uint64List.fromList([
+ // FIPS 180-4, Section 5.3.6.2
+ 0x22312194fc2bf72c,
+ 0x9f555fa3c84c64c2,
+ 0x2393b86b6f53b151,
+ 0x963877195940eabd,
+ 0x96283ee2a88effe3,
+ 0xbe5e1e2553863992,
+ 0x2b0199fc2c85b8aa,
+ 0x0eb72ddc81c52ca2,
+ ]),
+ );
}
final _noise64 = Uint64List.fromList([
diff --git a/pkgs/crypto/lib/src/sha512_slowsinks.dart b/pkgs/crypto/lib/src/sha512_slowsinks.dart
index 2dd64e0..97060f2 100644
--- a/pkgs/crypto/lib/src/sha512_slowsinks.dart
+++ b/pkgs/crypto/lib/src/sha512_slowsinks.dart
@@ -77,7 +77,12 @@
// http://tools.ietf.org/html/rfc6234.
void _shr(
- int bits, Uint32List word, int offset, Uint32List ret, int offsetR) {
+ int bits,
+ Uint32List word,
+ int offset,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] =
((bits < 32) && (bits >= 0)) ? (word[0 + offset] >> bits) : 0;
ret[1 + offsetR] = (bits > 32)
@@ -91,7 +96,12 @@
}
void _shl(
- int bits, Uint32List word, int offset, Uint32List ret, int offsetR) {
+ int bits,
+ Uint32List word,
+ int offset,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] = (bits > 32)
? (word[1 + offset] << (bits - 32))
: (bits == 32)
@@ -104,20 +114,38 @@
((bits < 32) && (bits >= 0)) ? (word[1 + offset] << bits) : 0;
}
- void _or(Uint32List word1, int offset1, Uint32List word2, int offset2,
- Uint32List ret, int offsetR) {
+ void _or(
+ Uint32List word1,
+ int offset1,
+ Uint32List word2,
+ int offset2,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] = word1[0 + offset1] | word2[0 + offset2];
ret[1 + offsetR] = word1[1 + offset1] | word2[1 + offset2];
}
- void _xor(Uint32List word1, int offset1, Uint32List word2, int offset2,
- Uint32List ret, int offsetR) {
+ void _xor(
+ Uint32List word1,
+ int offset1,
+ Uint32List word2,
+ int offset2,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] = word1[0 + offset1] ^ word2[0 + offset2];
ret[1 + offsetR] = word1[1 + offset1] ^ word2[1 + offset2];
}
- void _add(Uint32List word1, int offset1, Uint32List word2, int offset2,
- Uint32List ret, int offsetR) {
+ void _add(
+ Uint32List word1,
+ int offset1,
+ Uint32List word2,
+ int offset2,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[1 + offsetR] = word1[1 + offset1] + word2[1 + offset2];
ret[0 + offsetR] = word1[0 + offset1] +
word2[0 + offset2] +
@@ -154,7 +182,12 @@
// SHA rotate ((word >> bits) | (word << (64-bits)))
void _rotr(
- int bits, Uint32List word, int offset, Uint32List ret, int offsetR) {
+ int bits,
+ Uint32List word,
+ int offset,
+ Uint32List ret,
+ int offsetR,
+ ) {
_shr(bits, word, offset, _nums, _rotrIndex1);
_shl(64 - bits, word, offset, _nums, _rotrIndex2);
_or(_nums, _rotrIndex1, _nums, _rotrIndex2, ret, offsetR);
@@ -192,16 +225,32 @@
_xor(_nums, _sigIndex1, _nums, _sigIndex4, ret, offsetR);
}
- void _ch(Uint32List x, int offsetX, Uint32List y, int offsetY, Uint32List z,
- int offsetZ, Uint32List ret, int offsetR) {
+ void _ch(
+ Uint32List x,
+ int offsetX,
+ Uint32List y,
+ int offsetY,
+ Uint32List z,
+ int offsetZ,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] =
(x[0 + offsetX] & (y[0 + offsetY] ^ z[0 + offsetZ])) ^ z[0 + offsetZ];
ret[1 + offsetR] =
(x[1 + offsetX] & (y[1 + offsetY] ^ z[1 + offsetZ])) ^ z[1 + offsetZ];
}
- void _maj(Uint32List x, int offsetX, Uint32List y, int offsetY, Uint32List z,
- int offsetZ, Uint32List ret, int offsetR) {
+ void _maj(
+ Uint32List x,
+ int offsetX,
+ Uint32List y,
+ int offsetY,
+ Uint32List z,
+ int offsetZ,
+ Uint32List ret,
+ int offsetR,
+ ) {
ret[0 + offsetR] = (x[0 + offsetX] & (y[0 + offsetY] | z[0 + offsetZ])) |
(y[0 + offsetY] & z[0 + offsetZ]);
ret[1 + offsetR] = (x[1 + offsetX] & (y[1 + offsetY] | z[1 + offsetZ])) |
@@ -281,25 +330,26 @@
Sha384Sink(Sink<Digest> sink)
: super(
- sink,
- Uint32List.fromList([
- 0xcbbb9d5d,
- 0xc1059ed8,
- 0x629a292a,
- 0x367cd507,
- 0x9159015a,
- 0x3070dd17,
- 0x152fecd8,
- 0xf70e5939,
- 0x67332667,
- 0xffc00b31,
- 0x8eb44a87,
- 0x68581511,
- 0xdb0c2e0d,
- 0x64f98fa7,
- 0x47b5481d,
- 0xbefa4fa4,
- ]));
+ sink,
+ Uint32List.fromList([
+ 0xcbbb9d5d,
+ 0xc1059ed8,
+ 0x629a292a,
+ 0x367cd507,
+ 0x9159015a,
+ 0x3070dd17,
+ 0x152fecd8,
+ 0xf70e5939,
+ 0x67332667,
+ 0xffc00b31,
+ 0x8eb44a87,
+ 0x68581511,
+ 0xdb0c2e0d,
+ 0x64f98fa7,
+ 0x47b5481d,
+ 0xbefa4fa4,
+ ]),
+ );
}
/// The concrete implementation of `Sha512`.
@@ -338,18 +388,19 @@
Sha512224Sink(Sink<Digest> sink)
: super(
- sink,
- Uint32List.fromList([
- // FIPS 180-4, Section 5.3.6.1
- 0x8c3d37c8, 0x19544da2,
- 0x73e19966, 0x89dcd4d6,
- 0x1dfab7ae, 0x32ff9c82,
- 0x679dd514, 0x582f9fcf,
- 0x0f6d2b69, 0x7bd44da8,
- 0x77e36f73, 0x04c48942,
- 0x3f9d85a8, 0x6a1d36c8,
- 0x1112e6ad, 0x91d692a1,
- ]));
+ sink,
+ Uint32List.fromList([
+ // FIPS 180-4, Section 5.3.6.1
+ 0x8c3d37c8, 0x19544da2,
+ 0x73e19966, 0x89dcd4d6,
+ 0x1dfab7ae, 0x32ff9c82,
+ 0x679dd514, 0x582f9fcf,
+ 0x0f6d2b69, 0x7bd44da8,
+ 0x77e36f73, 0x04c48942,
+ 0x3f9d85a8, 0x6a1d36c8,
+ 0x1112e6ad, 0x91d692a1,
+ ]),
+ );
}
/// The concrete implementation of [Sha512/256].
@@ -362,16 +413,17 @@
Sha512256Sink(Sink<Digest> sink)
: super(
- sink,
- Uint32List.fromList([
- // FIPS 180-4, Section 5.3.6.2
- 0x22312194, 0xfc2bf72c,
- 0x9f555fa3, 0xc84c64c2,
- 0x2393b86b, 0x6f53b151,
- 0x96387719, 0x5940eabd,
- 0x96283ee2, 0xa88effe3,
- 0xbe5e1e25, 0x53863992,
- 0x2b0199fc, 0x2c85b8aa,
- 0x0eb72ddc, 0x81c52ca2,
- ]));
+ sink,
+ Uint32List.fromList([
+ // FIPS 180-4, Section 5.3.6.2
+ 0x22312194, 0xfc2bf72c,
+ 0x9f555fa3, 0xc84c64c2,
+ 0x2393b86b, 0x6f53b151,
+ 0x96387719, 0x5940eabd,
+ 0x96283ee2, 0xa88effe3,
+ 0xbe5e1e25, 0x53863992,
+ 0x2b0199fc, 0x2c85b8aa,
+ 0x0eb72ddc, 0x81c52ca2,
+ ]),
+ );
}
diff --git a/pkgs/crypto/pubspec.yaml b/pkgs/crypto/pubspec.yaml
index 9070ce9..b0cd647 100644
--- a/pkgs/crypto/pubspec.yaml
+++ b/pkgs/crypto/pubspec.yaml
@@ -1,5 +1,5 @@
name: crypto
-version: 3.0.6
+version: 3.0.7-wip
description: Implementations of SHA, MD5, and HMAC cryptographic functions.
repository: https://github.com/dart-lang/core/tree/main/pkgs/crypto
issue_tracker: https://github.com/dart-lang/core/issues?q=is%3Aissue+is%3Aopen+label%3Apackage%3Acrypto
diff --git a/pkgs/crypto/test/hmac_md5_test.dart b/pkgs/crypto/test/hmac_md5_test.dart
index 0cbcec0..f18f9e1 100644
--- a/pkgs/crypto/test/hmac_md5_test.dart
+++ b/pkgs/crypto/test/hmac_md5_test.dart
@@ -13,8 +13,12 @@
group('standard vector', () {
for (var i = 0; i < _inputs.length; i++) {
test(_macs[i], () {
- expectHmacEquals(md5, bytesFromHexString(_inputs[i]),
- bytesFromHexString(_keys[i]), _macs[i]);
+ expectHmacEquals(
+ md5,
+ bytesFromHexString(_inputs[i]),
+ bytesFromHexString(_keys[i]),
+ _macs[i],
+ );
});
}
});
diff --git a/pkgs/crypto/test/hmac_sha1_test.dart b/pkgs/crypto/test/hmac_sha1_test.dart
index c7dafa5..e97cec7 100644
--- a/pkgs/crypto/test/hmac_sha1_test.dart
+++ b/pkgs/crypto/test/hmac_sha1_test.dart
@@ -13,8 +13,12 @@
group('standard vector', () {
for (var i = 0; i < _inputs.length; i++) {
test(_macs[i], () {
- expectHmacEquals(sha1, bytesFromHexString(_inputs[i]),
- bytesFromHexString(_keys[i]), _macs[i]);
+ expectHmacEquals(
+ sha1,
+ bytesFromHexString(_inputs[i]),
+ bytesFromHexString(_keys[i]),
+ _macs[i],
+ );
});
}
});
diff --git a/pkgs/crypto/test/hmac_sha256_test.dart b/pkgs/crypto/test/hmac_sha256_test.dart
index 7b8cbab..3ed8508 100644
--- a/pkgs/crypto/test/hmac_sha256_test.dart
+++ b/pkgs/crypto/test/hmac_sha256_test.dart
@@ -13,8 +13,12 @@
group('standard vector', () {
for (var i = 0; i < _inputs.length; i++) {
test(_macs[i], () {
- expectHmacEquals(sha256, bytesFromHexString(_inputs[i]),
- bytesFromHexString(_keys[i]), _macs[i]);
+ expectHmacEquals(
+ sha256,
+ bytesFromHexString(_inputs[i]),
+ bytesFromHexString(_keys[i]),
+ _macs[i],
+ );
});
}
});
diff --git a/pkgs/crypto/test/hmac_sha2_test.dart b/pkgs/crypto/test/hmac_sha2_test.dart
index 4f2abfa..256bece 100644
--- a/pkgs/crypto/test/hmac_sha2_test.dart
+++ b/pkgs/crypto/test/hmac_sha2_test.dart
@@ -117,13 +117,21 @@
final keyBytes = bytesFromHexString(key);
final dataBytes = bytesFromHexString(data);
- expect(Hmac(sha224, keyBytes).convert(dataBytes).toString(),
- truncation ? startsWith(hmacSha224) : hmacSha224);
- expect(Hmac(sha256, keyBytes).convert(dataBytes).toString(),
- truncation ? startsWith(hmacSha256) : hmacSha256);
- expect(Hmac(sha384, keyBytes).convert(dataBytes).toString(),
- truncation ? startsWith(hmacSha384) : hmacSha384);
- expect(Hmac(sha512, keyBytes).convert(dataBytes).toString(),
- truncation ? startsWith(hmacSha512) : hmacSha512);
+ expect(
+ Hmac(sha224, keyBytes).convert(dataBytes).toString(),
+ truncation ? startsWith(hmacSha224) : hmacSha224,
+ );
+ expect(
+ Hmac(sha256, keyBytes).convert(dataBytes).toString(),
+ truncation ? startsWith(hmacSha256) : hmacSha256,
+ );
+ expect(
+ Hmac(sha384, keyBytes).convert(dataBytes).toString(),
+ truncation ? startsWith(hmacSha384) : hmacSha384,
+ );
+ expect(
+ Hmac(sha512, keyBytes).convert(dataBytes).toString(),
+ truncation ? startsWith(hmacSha512) : hmacSha512,
+ );
});
}
diff --git a/pkgs/crypto/test/sha1_test.dart b/pkgs/crypto/test/sha1_test.dart
index f5bb31d..0f6a3c8 100644
--- a/pkgs/crypto/test/sha1_test.dart
+++ b/pkgs/crypto/test/sha1_test.dart
@@ -31,11 +31,14 @@
test('close closes the underlying sink', () {
var inner = ChunkedConversionSink<Digest>.withCallback(
- expectAsync1((accumulated) {
- expect(accumulated.length, equals(1));
- expect(accumulated.first.toString(),
- equals('da39a3ee5e6b4b0d3255bfef95601890afd80709'));
- }));
+ expectAsync1((accumulated) {
+ expect(accumulated.length, equals(1));
+ expect(
+ accumulated.first.toString(),
+ equals('da39a3ee5e6b4b0d3255bfef95601890afd80709'),
+ );
+ }),
+ );
var outer = sha1.startChunkedConversion(inner);
outer.close();
@@ -45,8 +48,10 @@
group('standard vector', () {
for (var i = 0; i < _inputs.length; i++) {
test(_digests[i], () {
- expect(sha1.convert(bytesFromHexString(_inputs[i])).toString(),
- equals(_digests[i]));
+ expect(
+ sha1.convert(bytesFromHexString(_inputs[i])).toString(),
+ equals(_digests[i]),
+ );
});
}
});
@@ -60,8 +65,10 @@
hash.add(chunk);
}
hash.close();
- expect(sink.events.single.toString(),
- '5b088492c9f4778f409b7ae61477dec124c99033');
+ expect(
+ sink.events.single.toString(),
+ '5b088492c9f4778f409b7ae61477dec124c99033',
+ );
});
});
}
diff --git a/pkgs/crypto/test/sha256_test.dart b/pkgs/crypto/test/sha256_test.dart
index bd8d23f..be6bd43 100644
--- a/pkgs/crypto/test/sha256_test.dart
+++ b/pkgs/crypto/test/sha256_test.dart
@@ -16,15 +16,17 @@
group('SHA2-256', () {
group('with a chunked converter', () {
test('add may not be called after close', () {
- var sink =
- sha256.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha256.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
expect(() => sink.add([0]), throwsStateError);
});
test('close may be called multiple times', () {
- var sink =
- sha256.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha256.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
sink.close();
sink.close();
@@ -33,15 +35,17 @@
test('close closes the underlying sink', () {
var inner = ChunkedConversionSink<Digest>.withCallback(
- expectAsync1((accumulated) {
- expect(accumulated.length, equals(1));
- expect(
- accumulated.first.toString(),
- equals(
+ expectAsync1((accumulated) {
+ expect(accumulated.length, equals(1));
+ expect(
+ accumulated.first.toString(),
+ equals(
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b8'
- '55'),
- );
- }));
+ '55',
+ ),
+ );
+ }),
+ );
var outer = sha256.startChunkedConversion(inner);
outer.close();
@@ -49,23 +53,27 @@
});
test('vectors', () {
- expect('${sha256.convert('this is a test'.codeUnits)}',
- '2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c');
+ expect(
+ '${sha256.convert('this is a test'.codeUnits)}',
+ '2e99758548972a8e8822ad47fa1017ff72f06f3ff6a016851f45c398732bc50c',
+ );
});
});
group('SHA2-224', () {
group('with a chunked converter', () {
test('add may not be called after close', () {
- var sink =
- sha224.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha224.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
expect(() => sink.add([0]), throwsStateError);
});
test('close may be called multiple times', () {
- var sink =
- sha224.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha224.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
sink.close();
sink.close();
@@ -74,13 +82,16 @@
test('close closes the underlying sink', () {
var inner = ChunkedConversionSink<Digest>.withCallback(
- expectAsync1((accumulated) {
- expect(accumulated.length, equals(1));
- expect(
+ expectAsync1((accumulated) {
+ expect(accumulated.length, equals(1));
+ expect(
accumulated.first.toString(),
equals(
- 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f'));
- }));
+ 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f',
+ ),
+ );
+ }),
+ );
var outer = sha224.startChunkedConversion(inner);
outer.close();
@@ -88,16 +99,20 @@
});
test('vectors', () {
- expect('${sha224.convert('this is a test'.codeUnits)}',
- '52fa5d621db1c9f11602fc92d1e8d1115a9018f191de948944c4ac39');
+ expect(
+ '${sha224.convert('this is a test'.codeUnits)}',
+ '52fa5d621db1c9f11602fc92d1e8d1115a9018f191de948944c4ac39',
+ );
});
});
group('standard vector', () {
for (var i = 0; i < _inputs.length; i++) {
test(_digests[i], () {
- expect(sha256.convert(bytesFromHexString(_inputs[i])).toString(),
- equals(_digests[i]));
+ expect(
+ sha256.convert(bytesFromHexString(_inputs[i])).toString(),
+ equals(_digests[i]),
+ );
});
}
});
diff --git a/pkgs/crypto/test/sha512_test.dart b/pkgs/crypto/test/sha512_test.dart
index 07ad788..5fd183d 100644
--- a/pkgs/crypto/test/sha512_test.dart
+++ b/pkgs/crypto/test/sha512_test.dart
@@ -14,15 +14,17 @@
group('SHA2-384', () {
group('with a chunked converter', () {
test('add may not be called after close', () {
- var sink =
- sha384.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha384.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
expect(() => sink.add([0]), throwsStateError);
});
test('close may be called multiple times', () {
- var sink =
- sha384.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha384.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
sink.close();
sink.close();
@@ -31,14 +33,16 @@
test('close closes the underlying sink', () {
var inner = ChunkedConversionSink<Digest>.withCallback(
- expectAsync1((accumulated) {
- expect(accumulated.length, equals(1));
- expect(
- accumulated.first.toString(),
- equals(
- '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b'),
- );
- }));
+ expectAsync1((accumulated) {
+ expect(accumulated.length, equals(1));
+ expect(
+ accumulated.first.toString(),
+ equals(
+ '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b',
+ ),
+ );
+ }),
+ );
var outer = sha384.startChunkedConversion(inner);
outer.close();
@@ -49,15 +53,17 @@
group('SHA2-512', () {
group('with a chunked converter', () {
test('add may not be called after close', () {
- var sink =
- sha512.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha512.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
expect(() => sink.add([0]), throwsStateError);
});
test('close may be called multiple times', () {
- var sink =
- sha512.startChunkedConversion(StreamController<Digest>().sink);
+ var sink = sha512.startChunkedConversion(
+ StreamController<Digest>().sink,
+ );
sink.close();
sink.close();
sink.close();
@@ -66,13 +72,16 @@
test('close closes the underlying sink', () {
var inner = ChunkedConversionSink<Digest>.withCallback(
- expectAsync1((accumulated) {
- expect(accumulated.length, equals(1));
- expect(
+ expectAsync1((accumulated) {
+ expect(accumulated.length, equals(1));
+ expect(
accumulated.first.toString(),
equals(
- 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'));
- }));
+ 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e',
+ ),
+ );
+ }),
+ );
var outer = sha512.startChunkedConversion(inner);
outer.close();
diff --git a/pkgs/fixnum/CHANGELOG.md b/pkgs/fixnum/CHANGELOG.md
index 5bec83a..a505c3e 100644
--- a/pkgs/fixnum/CHANGELOG.md
+++ b/pkgs/fixnum/CHANGELOG.md
@@ -1,8 +1,9 @@
## 1.2.0-wip
-* Change `IntX` such that it implements `Comparable<IntX>`. This makes it
+- Change `IntX` such that it implements `Comparable<IntX>`. This makes it
possible for `IntX` (and in turn `Int64` and `Int32`) be used with methods
like `sortedBy` in the platform libraries.
+- Run `dart format` with the new style.
## 1.1.1
diff --git a/pkgs/fixnum/lib/src/int64.dart b/pkgs/fixnum/lib/src/int64.dart
index cb0e1cc..4c04321 100644
--- a/pkgs/fixnum/lib/src/int64.dart
+++ b/pkgs/fixnum/lib/src/int64.dart
@@ -801,7 +801,12 @@
}
static String _toRadixStringUnsigned(
- int radix, int d0, int d1, int d2, String sign) {
+ int radix,
+ int d0,
+ int d1,
+ int d2,
+ String sign,
+ ) {
if (d0 == 0 && d1 == 0 && d2 == 0) return '0';
// Rearrange components into five components where all but the most
@@ -934,7 +939,7 @@
33 * 33 * 33,
34 * 34 * 34,
35 * 35 * 35,
- 36 * 36 * 36
+ 36 * 36 * 36,
];
String toDebugString() => 'Int64[_l=$_l, _m=$_m, _h=$_h]';
@@ -995,16 +1000,17 @@
static const _RETURN_MOD = 3;
static Int64 _divideHelper(
- // up to 64 bits unsigned in a2/a1/a0 and b2/b1/b0
- int a0,
- int a1,
- int a2,
- bool aNeg, // input A.
- int b0,
- int b1,
- int b2,
- bool bNeg, // input B.
- int what) {
+ // up to 64 bits unsigned in a2/a1/a0 and b2/b1/b0
+ int a0,
+ int a1,
+ int a2,
+ bool aNeg, // input A.
+ int b0,
+ int b1,
+ int b2,
+ bool bNeg, // input B.
+ int what,
+ ) {
int q0 = 0, q1 = 0, q2 = 0; // result Q.
int r0 = 0, r1 = 0, r2 = 0; // result R.
@@ -1102,8 +1108,10 @@
// 0 <= R < B
assert(Int64.ZERO <= Int64._bits(r0, r1, r2));
- assert(r2 < b2 || // Handles case where B = -(MIN_VALUE)
- Int64._bits(r0, r1, r2) < Int64._bits(b0, b1, b2));
+ assert(
+ r2 < b2 || // Handles case where B = -(MIN_VALUE)
+ Int64._bits(r0, r1, r2) < Int64._bits(b0, b1, b2),
+ );
assert(what == _RETURN_DIV || what == _RETURN_MOD || what == _RETURN_REM);
if (what == _RETURN_DIV) {
diff --git a/pkgs/fixnum/test/int32_test.dart b/pkgs/fixnum/test/int32_test.dart
index 5e6c36a..ba47edd 100644
--- a/pkgs/fixnum/test/int32_test.dart
+++ b/pkgs/fixnum/test/int32_test.dart
@@ -84,8 +84,10 @@
expect(n3 * n2, Int32(-12186984));
expect(Int32(0x12345678) * Int32(0x22222222), Int32(-899716112));
expect(Int32(123456789) * Int32(987654321), Int32(-67153019));
- expect(Int32(0x12345678) * Int64(0x22222222),
- Int64.fromInts(0x026D60DC, 0xCA5F6BF0));
+ expect(
+ Int32(0x12345678) * Int64(0x22222222),
+ Int64.fromInts(0x026D60DC, 0xCA5F6BF0),
+ );
expect(Int32(123456789) * 987654321, Int32(-67153019));
});
@@ -104,16 +106,26 @@
});
test('remainder', () {
- expect(Int32(0x12345678).remainder(Int32(0x22)),
- Int32(0x12345678.remainder(0x22)));
- expect(Int32(0x12345678).remainder(Int32(-0x22)),
- Int32(0x12345678.remainder(-0x22)));
- expect(Int32(-0x12345678).remainder(Int32(-0x22)),
- Int32(-0x12345678.remainder(-0x22)));
- expect(Int32(-0x12345678).remainder(Int32(0x22)),
- Int32(-0x12345678.remainder(0x22)));
- expect(Int32(0x12345678).remainder(Int64(0x22)),
- Int32(0x12345678.remainder(0x22)));
+ expect(
+ Int32(0x12345678).remainder(Int32(0x22)),
+ Int32(0x12345678.remainder(0x22)),
+ );
+ expect(
+ Int32(0x12345678).remainder(Int32(-0x22)),
+ Int32(0x12345678.remainder(-0x22)),
+ );
+ expect(
+ Int32(-0x12345678).remainder(Int32(-0x22)),
+ Int32(-0x12345678.remainder(-0x22)),
+ );
+ expect(
+ Int32(-0x12345678).remainder(Int32(0x22)),
+ Int32(-0x12345678.remainder(0x22)),
+ );
+ expect(
+ Int32(0x12345678).remainder(Int64(0x22)),
+ Int32(0x12345678.remainder(0x22)),
+ );
});
test('abs', () {
@@ -239,24 +251,36 @@
group('bitwise operators', () {
test('&', () {
- expect(Int32(0x12345678) & Int32(0x22222222),
- Int32(0x12345678 & 0x22222222));
- expect(Int32(0x12345678) & Int64(0x22222222),
- Int64(0x12345678 & 0x22222222));
+ expect(
+ Int32(0x12345678) & Int32(0x22222222),
+ Int32(0x12345678 & 0x22222222),
+ );
+ expect(
+ Int32(0x12345678) & Int64(0x22222222),
+ Int64(0x12345678 & 0x22222222),
+ );
});
test('|', () {
- expect(Int32(0x12345678) | Int32(0x22222222),
- Int32(0x12345678 | 0x22222222));
- expect(Int32(0x12345678) | Int64(0x22222222),
- Int64(0x12345678 | 0x22222222));
+ expect(
+ Int32(0x12345678) | Int32(0x22222222),
+ Int32(0x12345678 | 0x22222222),
+ );
+ expect(
+ Int32(0x12345678) | Int64(0x22222222),
+ Int64(0x12345678 | 0x22222222),
+ );
});
test('^', () {
- expect(Int32(0x12345678) ^ Int32(0x22222222),
- Int32(0x12345678 ^ 0x22222222));
- expect(Int32(0x12345678) ^ Int64(0x22222222),
- Int64(0x12345678 ^ 0x22222222));
+ expect(
+ Int32(0x12345678) ^ Int32(0x22222222),
+ Int32(0x12345678 ^ 0x22222222),
+ );
+ expect(
+ Int32(0x12345678) ^ Int64(0x22222222),
+ Int64(0x12345678 ^ 0x22222222),
+ );
});
test('~', () {
diff --git a/pkgs/fixnum/test/int64_test.dart b/pkgs/fixnum/test/int64_test.dart
index e74d893..50297cb 100644
--- a/pkgs/fixnum/test/int64_test.dart
+++ b/pkgs/fixnum/test/int64_test.dart
@@ -20,10 +20,16 @@
checkBytes([0, 0, 0, 0, 0, 0, 0, 0], 0, 0);
checkBytes([1, 0, 0, 0, 0, 0, 0, 0], 0, 1);
checkBytes([1, 2, 3, 4, 5, 6, 7, 8], 0x08070605, 0x04030201);
- checkBytes([0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 0xffffffff,
- 0xfffffffe);
- checkBytes([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 0xffffffff,
- 0xffffffff);
+ checkBytes(
+ [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
+ 0xffffffff,
+ 0xfffffffe,
+ );
+ checkBytes(
+ [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
+ 0xffffffff,
+ 0xffffffff,
+ );
});
test('fromBytesBigEndian', () {
void checkBytes(List<int> bytes, int h, int l) {
@@ -33,10 +39,16 @@
checkBytes([0, 0, 0, 0, 0, 0, 0, 0], 0, 0);
checkBytes([0, 0, 0, 0, 0, 0, 0, 1], 0, 1);
checkBytes([8, 7, 6, 5, 4, 3, 2, 1], 0x08070605, 0x04030201);
- checkBytes([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe], 0xffffffff,
- 0xfffffffe);
- checkBytes([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], 0xffffffff,
- 0xffffffff);
+ checkBytes(
+ [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe],
+ 0xffffffff,
+ 0xfffffffe,
+ );
+ checkBytes(
+ [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
+ 0xffffffff,
+ 0xffffffff,
+ );
});
});
@@ -47,8 +59,11 @@
expect(
() => op(receiver, 'foo'),
throwsA(
- isA<ArgumentError>()
- .having((p0) => p0.toString(), 'toString', contains('"foo"')),
+ isA<ArgumentError>().having(
+ (p0) => p0.toString(),
+ 'toString',
+ contains('"foo"'),
+ ),
),
);
}
@@ -139,27 +154,36 @@
expect(Int64(100) * Int64.ZERO, Int64.ZERO);
expect(
- Int64.fromInts(0x12345678, 0x12345678) *
- Int64.fromInts(0x1234, 0x12345678),
- Int64.fromInts(0x7ff63f7c, 0x1df4d840));
+ Int64.fromInts(0x12345678, 0x12345678) *
+ Int64.fromInts(0x1234, 0x12345678),
+ Int64.fromInts(0x7ff63f7c, 0x1df4d840),
+ );
expect(
- Int64.fromInts(0xf2345678, 0x12345678) *
- Int64.fromInts(0x1234, 0x12345678),
- Int64.fromInts(0x7ff63f7c, 0x1df4d840));
+ Int64.fromInts(0xf2345678, 0x12345678) *
+ Int64.fromInts(0x1234, 0x12345678),
+ Int64.fromInts(0x7ff63f7c, 0x1df4d840),
+ );
expect(
- Int64.fromInts(0xf2345678, 0x12345678) *
- Int64.fromInts(0xffff1234, 0x12345678),
- Int64.fromInts(0x297e3f7c, 0x1df4d840));
+ Int64.fromInts(0xf2345678, 0x12345678) *
+ Int64.fromInts(0xffff1234, 0x12345678),
+ Int64.fromInts(0x297e3f7c, 0x1df4d840),
+ );
// RHS Int32
- expect(Int64(123456789) * Int32(987654321),
- Int64.fromInts(0x1b13114, 0xfbff5385));
- expect(Int64(123456789) * Int32(987654321),
- Int64.fromInts(0x1b13114, 0xfbff5385));
+ expect(
+ Int64(123456789) * Int32(987654321),
+ Int64.fromInts(0x1b13114, 0xfbff5385),
+ );
+ expect(
+ Int64(123456789) * Int32(987654321),
+ Int64.fromInts(0x1b13114, 0xfbff5385),
+ );
// Wraparound
- expect(Int64(123456789) * Int64(987654321),
- Int64.fromInts(0x1b13114, 0xfbff5385));
+ expect(
+ Int64(123456789) * Int64(987654321),
+ Int64.fromInts(0x1b13114, 0xfbff5385),
+ );
expect(Int64.MIN_VALUE * Int64(2), Int64.ZERO);
expect(Int64.MIN_VALUE * Int64(1), Int64.MIN_VALUE);
@@ -174,7 +198,9 @@
expect(deadBeef ~/ ten, Int64.fromInts(0xfcaaf97e, 0x63115fe5));
expect(Int64.ONE ~/ Int64.TWO, Int64.ZERO);
expect(
- Int64.MAX_VALUE ~/ Int64.TWO, Int64.fromInts(0x3fffffff, 0xffffffff));
+ Int64.MAX_VALUE ~/ Int64.TWO,
+ Int64.fromInts(0x3fffffff, 0xffffffff),
+ );
expect(Int64.ZERO ~/ Int64(1000), Int64.ZERO);
expect(Int64.MIN_VALUE ~/ Int64.MIN_VALUE, Int64.ONE);
expect(Int64(1000) ~/ Int64.MIN_VALUE, Int64.ZERO);
@@ -186,28 +212,50 @@
expect(Int64(-1000000000) ~/ Int64(8193), Int64(-122055));
expect(Int64(1000000000) ~/ Int64(8192), Int64(122070));
expect(Int64(1000000000) ~/ Int64(8193), Int64(122055));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00000400),
- Int64.fromInts(0x1fffff, 0xffffffff));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00040000),
- Int64.fromInts(0x1fff, 0xffffffff));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x04000000),
- Int64.fromInts(0x1f, 0xffffffff));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000004, 0x00000000),
- Int64(536870911));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000400, 0x00000000),
- Int64(2097151));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00040000, 0x00000000),
- Int64(8191));
expect(
- Int64.MAX_VALUE ~/ Int64.fromInts(0x04000000, 0x00000000), Int64(31));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00000300),
- Int64.fromInts(0x2AAAAA, 0xAAAAAAAA));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x30000000),
- Int64.fromInts(0x2, 0xAAAAAAAA));
- expect(Int64.MAX_VALUE ~/ Int64.fromInts(0x00300000, 0x00000000),
- Int64(0x2AA));
- expect(Int64.MAX_VALUE ~/ Int64(0x123456),
- Int64.fromInts(0x708, 0x002E9501));
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00000400),
+ Int64.fromInts(0x1fffff, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00040000),
+ Int64.fromInts(0x1fff, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x04000000),
+ Int64.fromInts(0x1f, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000004, 0x00000000),
+ Int64(536870911),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000400, 0x00000000),
+ Int64(2097151),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00040000, 0x00000000),
+ Int64(8191),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x04000000, 0x00000000),
+ Int64(31),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x00000300),
+ Int64.fromInts(0x2AAAAA, 0xAAAAAAAA),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00000000, 0x30000000),
+ Int64.fromInts(0x2, 0xAAAAAAAA),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64.fromInts(0x00300000, 0x00000000),
+ Int64(0x2AA),
+ );
+ expect(
+ Int64.MAX_VALUE ~/ Int64(0x123456),
+ Int64.fromInts(0x708, 0x002E9501),
+ );
expect(Int64.MAX_VALUE % Int64(0x123456), Int64(0x3BDA9));
expect(Int64(5) ~/ Int64(5), Int64.ONE);
expect(Int64(1000) ~/ Int64(3), Int64(333));
@@ -216,26 +264,32 @@
expect(Int64(-1000) ~/ Int64(-3), Int64(333));
expect(Int64(3) ~/ Int64(1000), Int64.ZERO);
expect(
- Int64.fromInts(0x12345678, 0x12345678) ~/ Int64.fromInts(0x0, 0x123),
- Int64.fromInts(0x1003d0, 0xe84f5ae8));
+ Int64.fromInts(0x12345678, 0x12345678) ~/ Int64.fromInts(0x0, 0x123),
+ Int64.fromInts(0x1003d0, 0xe84f5ae8),
+ );
expect(
- Int64.fromInts(0x12345678, 0x12345678) ~/
- Int64.fromInts(0x1234, 0x12345678),
- Int64.fromInts(0x0, 0x10003));
+ Int64.fromInts(0x12345678, 0x12345678) ~/
+ Int64.fromInts(0x1234, 0x12345678),
+ Int64.fromInts(0x0, 0x10003),
+ );
expect(
- Int64.fromInts(0xf2345678, 0x12345678) ~/
- Int64.fromInts(0x1234, 0x12345678),
- Int64.fromInts(0xffffffff, 0xffff3dfe));
+ Int64.fromInts(0xf2345678, 0x12345678) ~/
+ Int64.fromInts(0x1234, 0x12345678),
+ Int64.fromInts(0xffffffff, 0xffff3dfe),
+ );
expect(
- Int64.fromInts(0xf2345678, 0x12345678) ~/
- Int64.fromInts(0xffff1234, 0x12345678),
- Int64.fromInts(0x0, 0xeda));
+ Int64.fromInts(0xf2345678, 0x12345678) ~/
+ Int64.fromInts(0xffff1234, 0x12345678),
+ Int64.fromInts(0x0, 0xeda),
+ );
expect(Int64(829893893) ~/ Int32(1919), Int32(432461));
expect(Int64(829893893) ~/ Int64(1919), Int32(432461));
expect(Int64(829893893) ~/ 1919, Int32(432461));
expect(() => Int64(1) ~/ Int64.ZERO, throwsA(isUnsupportedError));
expect(
- Int64.MIN_VALUE ~/ Int64(2), Int64.fromInts(0xc0000000, 0x00000000));
+ Int64.MIN_VALUE ~/ Int64(2),
+ Int64.fromInts(0xc0000000, 0x00000000),
+ );
expect(Int64.MIN_VALUE ~/ Int64(1), Int64.MIN_VALUE);
expect(Int64.MIN_VALUE ~/ Int64(-1), Int64.MIN_VALUE);
expect(() => Int64(17) ~/ Int64.ZERO, throwsA(isUnsupportedError));
@@ -255,30 +309,54 @@
expect(Int64(-1000000000) % Int64(8193), Int64(4808));
expect(Int64(1000000000) % Int64(8192), Int64(2560));
expect(Int64(1000000000) % Int64(8193), Int64(3385));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x00000400),
- Int64.fromInts(0x0, 0x3ff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x00040000),
- Int64.fromInts(0x0, 0x3ffff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x04000000),
- Int64.fromInts(0x0, 0x3ffffff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00000004, 0x00000000),
- Int64.fromInts(0x3, 0xffffffff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00000400, 0x00000000),
- Int64.fromInts(0x3ff, 0xffffffff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x00040000, 0x00000000),
- Int64.fromInts(0x3ffff, 0xffffffff));
- expect(Int64.MAX_VALUE % Int64.fromInts(0x04000000, 0x00000000),
- Int64.fromInts(0x3ffffff, 0xffffffff));
- expect(Int64(0x12345678).remainder(Int64(0x22)),
- Int64(0x12345678.remainder(0x22)));
- expect(Int64(0x12345678).remainder(Int64(-0x22)),
- Int64(0x12345678.remainder(-0x22)));
- expect(Int64(-0x12345678).remainder(Int64(-0x22)),
- Int64(-0x12345678.remainder(-0x22)));
- expect(Int64(-0x12345678).remainder(Int64(0x22)),
- Int64(-0x12345678.remainder(0x22)));
- expect(Int32(0x12345678).remainder(Int64(0x22)),
- Int64(0x12345678.remainder(0x22)));
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x00000400),
+ Int64.fromInts(0x0, 0x3ff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x00040000),
+ Int64.fromInts(0x0, 0x3ffff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00000000, 0x04000000),
+ Int64.fromInts(0x0, 0x3ffffff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00000004, 0x00000000),
+ Int64.fromInts(0x3, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00000400, 0x00000000),
+ Int64.fromInts(0x3ff, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x00040000, 0x00000000),
+ Int64.fromInts(0x3ffff, 0xffffffff),
+ );
+ expect(
+ Int64.MAX_VALUE % Int64.fromInts(0x04000000, 0x00000000),
+ Int64.fromInts(0x3ffffff, 0xffffffff),
+ );
+ expect(
+ Int64(0x12345678).remainder(Int64(0x22)),
+ Int64(0x12345678.remainder(0x22)),
+ );
+ expect(
+ Int64(0x12345678).remainder(Int64(-0x22)),
+ Int64(0x12345678.remainder(-0x22)),
+ );
+ expect(
+ Int64(-0x12345678).remainder(Int64(-0x22)),
+ Int64(-0x12345678.remainder(-0x22)),
+ );
+ expect(
+ Int64(-0x12345678).remainder(Int64(0x22)),
+ Int64(-0x12345678.remainder(0x22)),
+ );
+ expect(
+ Int32(0x12345678).remainder(Int64(0x22)),
+ Int64(0x12345678.remainder(0x22)),
+ );
argumentErrorTest((a, b) => a % b);
});
@@ -397,7 +475,9 @@
expect(Int64(-10), equals(Int64(-10)));
expect(Int64(-10) != Int64(-10), false);
expect(
- Int64(-10) == -10, isTrue); // ignore: unrelated_type_equality_checks
+ Int64(-10) == -10,
+ isTrue,
+ ); // ignore: unrelated_type_equality_checks
expect(Int64(-10), isNot(equals(-9)));
expect(largePos, equals(largePos));
expect(largePos, isNot(equals(largePosPlusOne)));
@@ -491,10 +571,14 @@
group('bitshift operators', () {
test('<<', () {
- expect(Int64.fromInts(0x12341234, 0x45674567) << 10,
- Int64.fromInts(0xd048d115, 0x9d159c00));
- expect(Int64.fromInts(0x92341234, 0x45674567) << 10,
- Int64.fromInts(0xd048d115, 0x9d159c00));
+ expect(
+ Int64.fromInts(0x12341234, 0x45674567) << 10,
+ Int64.fromInts(0xd048d115, 0x9d159c00),
+ );
+ expect(
+ Int64.fromInts(0x92341234, 0x45674567) << 10,
+ Int64.fromInts(0xd048d115, 0x9d159c00),
+ );
expect(Int64(-1) << 5, Int64(-32));
expect(Int64(-1) << 0, Int64(-1));
expect(Int64(42) << 64, Int64.ZERO);
@@ -504,96 +588,176 @@
test('>>', () {
expect((Int64.MIN_VALUE >> 13).toString(), '-1125899906842624');
- expect(Int64.fromInts(0x12341234, 0x45674567) >> 10,
- Int64.fromInts(0x48d04, 0x8d1159d1));
- expect(Int64.fromInts(0x92341234, 0x45674567) >> 10,
- Int64.fromInts(0xffe48d04, 0x8d1159d1));
+ expect(
+ Int64.fromInts(0x12341234, 0x45674567) >> 10,
+ Int64.fromInts(0x48d04, 0x8d1159d1),
+ );
+ expect(
+ Int64.fromInts(0x92341234, 0x45674567) >> 10,
+ Int64.fromInts(0xffe48d04, 0x8d1159d1),
+ );
expect(Int64.fromInts(0xFFFFFFF, 0xFFFFFFFF) >> 34, Int64(67108863));
expect(Int64(42) >> 64, Int64.ZERO);
expect(Int64(42) >> 65, Int64.ZERO);
for (int n = 0; n <= 66; n++) {
expect(Int64(-1) >> n, Int64(-1));
}
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 8,
- Int64.fromInts(0x00723456, 0x789abcde));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 16,
- Int64.fromInts(0x00007234, 0x56789abc));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 24,
- Int64.fromInts(0x00000072, 0x3456789a));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 28,
- Int64.fromInts(0x00000007, 0x23456789));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 32,
- Int64.fromInts(0x00000000, 0x72345678));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 36,
- Int64.fromInts(0x00000000, 0x07234567));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 40,
- Int64.fromInts(0x00000000, 0x00723456));
- expect(Int64.fromInts(0x72345678, 0x9abcde00) >> 44,
- Int64.fromInts(0x00000000, 0x00072345));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0) >> 48,
- Int64.fromInts(0x00000000, 0x00007234));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 8,
- Int64.fromInts(0xff923456, 0x789abcde));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 16,
- Int64.fromInts(0xffff9234, 0x56789abc));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 24,
- Int64.fromInts(0xffffff92, 0x3456789a));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 28,
- Int64.fromInts(0xfffffff9, 0x23456789));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 32,
- Int64.fromInts(0xffffffff, 0x92345678));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 36,
- Int64.fromInts(0xffffffff, 0xf9234567));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 40,
- Int64.fromInts(0xffffffff, 0xff923456));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 44,
- Int64.fromInts(0xffffffff, 0xfff92345));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0) >> 48,
- Int64.fromInts(0xffffffff, 0xffff9234));
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 8,
+ Int64.fromInts(0x00723456, 0x789abcde),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 16,
+ Int64.fromInts(0x00007234, 0x56789abc),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 24,
+ Int64.fromInts(0x00000072, 0x3456789a),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 28,
+ Int64.fromInts(0x00000007, 0x23456789),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 32,
+ Int64.fromInts(0x00000000, 0x72345678),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 36,
+ Int64.fromInts(0x00000000, 0x07234567),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 40,
+ Int64.fromInts(0x00000000, 0x00723456),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcde00) >> 44,
+ Int64.fromInts(0x00000000, 0x00072345),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0) >> 48,
+ Int64.fromInts(0x00000000, 0x00007234),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 8,
+ Int64.fromInts(0xff923456, 0x789abcde),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 16,
+ Int64.fromInts(0xffff9234, 0x56789abc),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 24,
+ Int64.fromInts(0xffffff92, 0x3456789a),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 28,
+ Int64.fromInts(0xfffffff9, 0x23456789),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 32,
+ Int64.fromInts(0xffffffff, 0x92345678),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 36,
+ Int64.fromInts(0xffffffff, 0xf9234567),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 40,
+ Int64.fromInts(0xffffffff, 0xff923456),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 44,
+ Int64.fromInts(0xffffffff, 0xfff92345),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0) >> 48,
+ Int64.fromInts(0xffffffff, 0xffff9234),
+ );
expect(() => Int64(17) >> -1, throwsArgumentError);
});
test('shiftRightUnsigned', () {
- expect(Int64.fromInts(0x12341234, 0x45674567).shiftRightUnsigned(10),
- Int64.fromInts(0x48d04, 0x8d1159d1));
- expect(Int64.fromInts(0x92341234, 0x45674567).shiftRightUnsigned(10),
- Int64.fromInts(0x248d04, 0x8d1159d1));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(8),
- Int64.fromInts(0x00723456, 0x789abcde));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(16),
- Int64.fromInts(0x00007234, 0x56789abc));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(24),
- Int64.fromInts(0x00000072, 0x3456789a));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(28),
- Int64.fromInts(0x00000007, 0x23456789));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(32),
- Int64.fromInts(0x00000000, 0x72345678));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(36),
- Int64.fromInts(0x00000000, 0x07234567));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(40),
- Int64.fromInts(0x00000000, 0x00723456));
- expect(Int64.fromInts(0x72345678, 0x9abcde00).shiftRightUnsigned(44),
- Int64.fromInts(0x00000000, 0x00072345));
- expect(Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(48),
- Int64.fromInts(0x00000000, 0x00007234));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(8),
- Int64.fromInts(0x00923456, 0x789abcde));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(16),
- Int64.fromInts(0x00009234, 0x56789abc));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(24),
- Int64.fromInts(0x00000092, 0x3456789a));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(28),
- Int64.fromInts(0x00000009, 0x23456789));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(32),
- Int64.fromInts(0x00000000, 0x92345678));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(36),
- Int64.fromInts(0x00000000, 0x09234567));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(40),
- Int64.fromInts(0x00000000, 0x00923456));
- expect(Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(44),
- Int64.fromInts(0x00000000, 0x00092345));
- expect(Int64.fromInts(0x00000000, 0x00009234),
- Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(48));
+ expect(
+ Int64.fromInts(0x12341234, 0x45674567).shiftRightUnsigned(10),
+ Int64.fromInts(0x48d04, 0x8d1159d1),
+ );
+ expect(
+ Int64.fromInts(0x92341234, 0x45674567).shiftRightUnsigned(10),
+ Int64.fromInts(0x248d04, 0x8d1159d1),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(8),
+ Int64.fromInts(0x00723456, 0x789abcde),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(16),
+ Int64.fromInts(0x00007234, 0x56789abc),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(24),
+ Int64.fromInts(0x00000072, 0x3456789a),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(28),
+ Int64.fromInts(0x00000007, 0x23456789),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(32),
+ Int64.fromInts(0x00000000, 0x72345678),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(36),
+ Int64.fromInts(0x00000000, 0x07234567),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(40),
+ Int64.fromInts(0x00000000, 0x00723456),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcde00).shiftRightUnsigned(44),
+ Int64.fromInts(0x00000000, 0x00072345),
+ );
+ expect(
+ Int64.fromInts(0x72345678, 0x9abcdef0).shiftRightUnsigned(48),
+ Int64.fromInts(0x00000000, 0x00007234),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(8),
+ Int64.fromInts(0x00923456, 0x789abcde),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(16),
+ Int64.fromInts(0x00009234, 0x56789abc),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(24),
+ Int64.fromInts(0x00000092, 0x3456789a),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(28),
+ Int64.fromInts(0x00000009, 0x23456789),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(32),
+ Int64.fromInts(0x00000000, 0x92345678),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(36),
+ Int64.fromInts(0x00000000, 0x09234567),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(40),
+ Int64.fromInts(0x00000000, 0x00923456),
+ );
+ expect(
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(44),
+ Int64.fromInts(0x00000000, 0x00092345),
+ );
+ expect(
+ Int64.fromInts(0x00000000, 0x00009234),
+ Int64.fromInts(0x92345678, 0x9abcdef0).shiftRightUnsigned(48),
+ );
expect(Int64(-1).shiftRightUnsigned(64), Int64.ZERO);
expect(Int64(1).shiftRightUnsigned(64), Int64.ZERO);
expect(() => Int64(17).shiftRightUnsigned(-1), throwsArgumentError);
@@ -605,9 +769,13 @@
expect(Int64.MIN_VALUE << 0, Int64.MIN_VALUE);
expect(Int64.MIN_VALUE << 1, Int64(0));
expect(
- (-Int64.fromInts(8, 0)) >> 1, Int64.fromInts(0xfffffffc, 0x00000000));
- expect((-Int64.fromInts(8, 0)).shiftRightUnsigned(1),
- Int64.fromInts(0x7ffffffc, 0x0));
+ (-Int64.fromInts(8, 0)) >> 1,
+ Int64.fromInts(0xfffffffc, 0x00000000),
+ );
+ expect(
+ (-Int64.fromInts(8, 0)).shiftRightUnsigned(1),
+ Int64.fromInts(0x7ffffffc, 0x0),
+ );
});
});
@@ -652,24 +820,42 @@
expect(Int64(4503599627370496).toDouble(), same(4503599627370496.0));
expect(Int64(-4503599627370495).toDouble(), same(-4503599627370495.0));
expect(Int64(-4503599627370496).toDouble(), same(-4503599627370496.0));
- expect(Int64.parseInt('-10000000000000000').toDouble().toStringAsFixed(1),
- '-10000000000000000.0');
- expect(Int64.parseInt('-10000000000000001').toDouble().toStringAsFixed(1),
- '-10000000000000000.0');
- expect(Int64.parseInt('-10000000000000002').toDouble().toStringAsFixed(1),
- '-10000000000000002.0');
- expect(Int64.parseInt('-10000000000000003').toDouble().toStringAsFixed(1),
- '-10000000000000004.0');
- expect(Int64.parseInt('-10000000000000004').toDouble().toStringAsFixed(1),
- '-10000000000000004.0');
- expect(Int64.parseInt('-10000000000000005').toDouble().toStringAsFixed(1),
- '-10000000000000004.0');
- expect(Int64.parseInt('-10000000000000006').toDouble().toStringAsFixed(1),
- '-10000000000000006.0');
- expect(Int64.parseInt('-10000000000000007').toDouble().toStringAsFixed(1),
- '-10000000000000008.0');
- expect(Int64.parseInt('-10000000000000008').toDouble().toStringAsFixed(1),
- '-10000000000000008.0');
+ expect(
+ Int64.parseInt('-10000000000000000').toDouble().toStringAsFixed(1),
+ '-10000000000000000.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000001').toDouble().toStringAsFixed(1),
+ '-10000000000000000.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000002').toDouble().toStringAsFixed(1),
+ '-10000000000000002.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000003').toDouble().toStringAsFixed(1),
+ '-10000000000000004.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000004').toDouble().toStringAsFixed(1),
+ '-10000000000000004.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000005').toDouble().toStringAsFixed(1),
+ '-10000000000000004.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000006').toDouble().toStringAsFixed(1),
+ '-10000000000000006.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000007').toDouble().toStringAsFixed(1),
+ '-10000000000000008.0',
+ );
+ expect(
+ Int64.parseInt('-10000000000000008').toDouble().toStringAsFixed(1),
+ '-10000000000000008.0',
+ );
});
test('toInt', () {
@@ -702,12 +888,36 @@
test('toBytes', () {
expect(Int64(0).toBytes(), [0, 0, 0, 0, 0, 0, 0, 0]);
- expect(Int64.fromInts(0x08070605, 0x04030201).toBytes(),
- [1, 2, 3, 4, 5, 6, 7, 8]);
- expect(Int64.fromInts(0x01020304, 0x05060708).toBytes(),
- [8, 7, 6, 5, 4, 3, 2, 1]);
- expect(Int64(-1).toBytes(),
- [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
+ expect(Int64.fromInts(0x08070605, 0x04030201).toBytes(), [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ ]);
+ expect(Int64.fromInts(0x01020304, 0x05060708).toBytes(), [
+ 8,
+ 7,
+ 6,
+ 5,
+ 4,
+ 3,
+ 2,
+ 1,
+ ]);
+ expect(Int64(-1).toBytes(), [
+ 0xff,
+ 0xff,
+ 0xff,
+ 0xff,
+ 0xff,
+ 0xff,
+ 0xff,
+ 0xff,
+ ]);
});
});
@@ -859,19 +1069,27 @@
Int64 deadbeef12341234 = Int64.fromInts(0xDEADBEEF, 0x12341234);
expect(Int64.ZERO.toHexString(), '0');
expect(deadbeef12341234.toHexString(), 'DEADBEEF12341234');
- expect(Int64.fromInts(0x17678A7, 0xDEF01234).toHexString(),
- '17678A7DEF01234');
+ expect(
+ Int64.fromInts(0x17678A7, 0xDEF01234).toHexString(),
+ '17678A7DEF01234',
+ );
expect(Int64(123456789).toHexString(), '75BCD15');
});
test('toRadixString', () {
expect(Int64(123456789).toRadixString(5), '223101104124');
- expect(Int64.MIN_VALUE.toRadixString(2),
- '-1000000000000000000000000000000000000000000000000000000000000000');
- expect(Int64.MIN_VALUE.toRadixString(3),
- '-2021110011022210012102010021220101220222');
- expect(Int64.MIN_VALUE.toRadixString(4),
- '-20000000000000000000000000000000');
+ expect(
+ Int64.MIN_VALUE.toRadixString(2),
+ '-1000000000000000000000000000000000000000000000000000000000000000',
+ );
+ expect(
+ Int64.MIN_VALUE.toRadixString(3),
+ '-2021110011022210012102010021220101220222',
+ );
+ expect(
+ Int64.MIN_VALUE.toRadixString(4),
+ '-20000000000000000000000000000000',
+ );
expect(Int64.MIN_VALUE.toRadixString(5), '-1104332401304422434310311213');
expect(Int64.MIN_VALUE.toRadixString(6), '-1540241003031030222122212');
expect(Int64.MIN_VALUE.toRadixString(7), '-22341010611245052052301');
@@ -884,12 +1102,18 @@
expect(Int64.MIN_VALUE.toRadixString(14), '-4340724c6c71dc7a8');
expect(Int64.MIN_VALUE.toRadixString(15), '-160e2ad3246366808');
expect(Int64.MIN_VALUE.toRadixString(16), '-8000000000000000');
- expect(Int64.MAX_VALUE.toRadixString(2),
- '111111111111111111111111111111111111111111111111111111111111111');
- expect(Int64.MAX_VALUE.toRadixString(3),
- '2021110011022210012102010021220101220221');
expect(
- Int64.MAX_VALUE.toRadixString(4), '13333333333333333333333333333333');
+ Int64.MAX_VALUE.toRadixString(2),
+ '111111111111111111111111111111111111111111111111111111111111111',
+ );
+ expect(
+ Int64.MAX_VALUE.toRadixString(3),
+ '2021110011022210012102010021220101220221',
+ );
+ expect(
+ Int64.MAX_VALUE.toRadixString(4),
+ '13333333333333333333333333333333',
+ );
expect(Int64.MAX_VALUE.toRadixString(5), '1104332401304422434310311212');
expect(Int64.MAX_VALUE.toRadixString(6), '1540241003031030222122211');
expect(Int64.MAX_VALUE.toRadixString(7), '22341010611245052052300');
diff --git a/pkgs/fixnum/test/int_64_vm_test.dart b/pkgs/fixnum/test/int_64_vm_test.dart
index 2d28da3..173e86d 100644
--- a/pkgs/fixnum/test/int_64_vm_test.dart
+++ b/pkgs/fixnum/test/int_64_vm_test.dart
@@ -11,24 +11,42 @@
void main() {
group('conversions', () {
test('toInt', () {
- expect(Int64.parseInt('-10000000000000000').toInt(),
- same(-10000000000000000));
- expect(Int64.parseInt('-10000000000000001').toInt(),
- same(-10000000000000001));
- expect(Int64.parseInt('-10000000000000002').toInt(),
- same(-10000000000000002));
- expect(Int64.parseInt('-10000000000000003').toInt(),
- same(-10000000000000003));
- expect(Int64.parseInt('-10000000000000004').toInt(),
- same(-10000000000000004));
- expect(Int64.parseInt('-10000000000000005').toInt(),
- same(-10000000000000005));
- expect(Int64.parseInt('-10000000000000006').toInt(),
- same(-10000000000000006));
- expect(Int64.parseInt('-10000000000000007').toInt(),
- same(-10000000000000007));
- expect(Int64.parseInt('-10000000000000008').toInt(),
- same(-10000000000000008));
+ expect(
+ Int64.parseInt('-10000000000000000').toInt(),
+ same(-10000000000000000),
+ );
+ expect(
+ Int64.parseInt('-10000000000000001').toInt(),
+ same(-10000000000000001),
+ );
+ expect(
+ Int64.parseInt('-10000000000000002').toInt(),
+ same(-10000000000000002),
+ );
+ expect(
+ Int64.parseInt('-10000000000000003').toInt(),
+ same(-10000000000000003),
+ );
+ expect(
+ Int64.parseInt('-10000000000000004').toInt(),
+ same(-10000000000000004),
+ );
+ expect(
+ Int64.parseInt('-10000000000000005').toInt(),
+ same(-10000000000000005),
+ );
+ expect(
+ Int64.parseInt('-10000000000000006').toInt(),
+ same(-10000000000000006),
+ );
+ expect(
+ Int64.parseInt('-10000000000000007').toInt(),
+ same(-10000000000000007),
+ );
+ expect(
+ Int64.parseInt('-10000000000000008').toInt(),
+ same(-10000000000000008),
+ );
});
});
diff --git a/pkgs/lints/CHANGELOG.md b/pkgs/lints/CHANGELOG.md
index 49b9398..ff99d82 100644
--- a/pkgs/lints/CHANGELOG.md
+++ b/pkgs/lints/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 6.0.1-wip
+
+- Run `dart format` with the new style.
+
## 6.0.0
- `core`:
diff --git a/pkgs/lints/pubspec.yaml b/pkgs/lints/pubspec.yaml
index a6bc636..8059666 100644
--- a/pkgs/lints/pubspec.yaml
+++ b/pkgs/lints/pubspec.yaml
@@ -1,5 +1,5 @@
name: lints
-version: 6.0.0
+version: 6.0.1-wip
description: >
Official Dart lint rules. Defines the 'core' and 'recommended' set of lints
suggested by the Dart team.
diff --git a/pkgs/lints/tool/gen_docs.dart b/pkgs/lints/tool/gen_docs.dart
index e081893..54a99ad 100644
--- a/pkgs/lints/tool/gen_docs.dart
+++ b/pkgs/lints/tool/gen_docs.dart
@@ -186,11 +186,10 @@
if (ruleMeta == null) {
stderr.writeln("WARNING: Missing rule information for rule: $rule");
}
- final description =
- (ruleMeta?['description'] ?? '')
- .replaceAll('\n', ' ')
- .replaceAll(RegExp(r'\s+'), ' ')
- .trim();
+ final description = (ruleMeta?['description'] ?? '')
+ .replaceAll('\n', ' ')
+ .replaceAll(RegExp(r'\s+'), ' ')
+ .trim();
final hasFix = ruleMeta?['fixStatus'] == 'hasFix';
final fixDesc = hasFix ? '✅' : '';
diff --git a/pkgs/lints/tool/validate_lib.dart b/pkgs/lints/tool/validate_lib.dart
index 388a7f8..38b1ce8 100644
--- a/pkgs/lints/tool/validate_lib.dart
+++ b/pkgs/lints/tool/validate_lib.dart
@@ -9,12 +9,11 @@
void main(List<String> args) {
print('Validating that there are no .dart source files in lib/ ...');
- final dartSourceFiles =
- Directory('lib')
- .listSync(recursive: true)
- .whereType<File>()
- .where((file) => p.extension(file.path) == '.dart')
- .toList();
+ final dartSourceFiles = Directory('lib')
+ .listSync(recursive: true)
+ .whereType<File>()
+ .where((file) => p.extension(file.path) == '.dart')
+ .toList();
if (dartSourceFiles.isEmpty) {
print('No Dart files found.');
diff --git a/pkgs/logging/CHANGELOG.md b/pkgs/logging/CHANGELOG.md
index 088183c..d32a8dc 100644
--- a/pkgs/logging/CHANGELOG.md
+++ b/pkgs/logging/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 1.3.1-wip
+
+- Run `dart format` with the new style.
+
## 1.3.0
* Override empty stack traces for trace level events.
diff --git a/pkgs/logging/lib/src/level.dart b/pkgs/logging/lib/src/level.dart
index 3669433..8453d8e 100644
--- a/pkgs/logging/lib/src/level.dart
+++ b/pkgs/logging/lib/src/level.dart
@@ -63,7 +63,7 @@
WARNING,
SEVERE,
SHOUT,
- OFF
+ OFF,
];
@override
diff --git a/pkgs/logging/lib/src/log_record.dart b/pkgs/logging/lib/src/log_record.dart
index 8a0ee61..38f065a 100644
--- a/pkgs/logging/lib/src/log_record.dart
+++ b/pkgs/logging/lib/src/log_record.dart
@@ -36,9 +36,15 @@
/// Zone of the calling code which resulted in this LogRecord.
final Zone? zone;
- LogRecord(this.level, this.message, this.loggerName,
- [this.error, this.stackTrace, this.zone, this.object])
- : time = DateTime.now(),
+ LogRecord(
+ this.level,
+ this.message,
+ this.loggerName, [
+ this.error,
+ this.stackTrace,
+ this.zone,
+ this.object,
+ ]) : time = DateTime.now(),
sequenceNumber = LogRecord._nextNumber++;
@override
diff --git a/pkgs/logging/lib/src/logger.dart b/pkgs/logging/lib/src/logger.dart
index d9fa254..1e0cd5f 100644
--- a/pkgs/logging/lib/src/logger.dart
+++ b/pkgs/logging/lib/src/logger.dart
@@ -135,12 +135,14 @@
set level(Level? value) {
if (!hierarchicalLoggingEnabled && parent != null) {
throw UnsupportedError(
- 'Please set "hierarchicalLoggingEnabled" to true if you want to '
- 'change the level on a non-root logger.');
+ 'Please set "hierarchicalLoggingEnabled" to true if you want to '
+ 'change the level on a non-root logger.',
+ );
}
if (parent == null && value == null) {
throw UnsupportedError(
- 'Cannot set the level to `null` on a logger with no parent.');
+ 'Cannot set the level to `null` on a logger with no parent.',
+ );
}
final isLevelChanged = _level != value;
_level = value;
@@ -206,8 +208,13 @@
/// If this record is logged at a level equal to or higher than
/// [recordStackTraceAtLevel] and [stackTrace] is `null` or [StackTrace.empty]
/// it will be defaulted to the current stack trace for this call.
- void log(Level logLevel, Object? message,
- [Object? error, StackTrace? stackTrace, Zone? zone]) {
+ void log(
+ Level logLevel,
+ Object? message, [
+ Object? error,
+ StackTrace? stackTrace,
+ Zone? zone,
+ ]) {
Object? object;
if (isLoggable(logLevel)) {
if (message is Function) {
@@ -229,8 +236,15 @@
}
zone ??= Zone.current;
- final record =
- LogRecord(logLevel, msg, fullName, error, stackTrace, zone, object);
+ final record = LogRecord(
+ logLevel,
+ msg,
+ fullName,
+ error,
+ stackTrace,
+ zone,
+ object,
+ );
if (parent == null) {
_publish(record);
@@ -304,7 +318,9 @@
Stream<LogRecord> _getStream() {
if (hierarchicalLoggingEnabled || parent == null) {
- return (_controller ??= StreamController<LogRecord>.broadcast(sync: true))
+ return (_controller ??= StreamController<LogRecord>.broadcast(
+ sync: true,
+ ))
.stream;
} else {
return root._getStream();
diff --git a/pkgs/logging/pubspec.yaml b/pkgs/logging/pubspec.yaml
index 30b2652..a1c0fca 100644
--- a/pkgs/logging/pubspec.yaml
+++ b/pkgs/logging/pubspec.yaml
@@ -1,5 +1,5 @@
name: logging
-version: 1.3.0
+version: 1.3.1-wip
description: >-
Provides APIs for debugging and error logging, similar to loggers in other
languages, such as the Closure JS Logger and java.util.logging.Logger.
diff --git a/pkgs/logging/test/logging_test.dart b/pkgs/logging/test/logging_test.dart
index 6bff3d8..320e277 100644
--- a/pkgs/logging/test/logging_test.dart
+++ b/pkgs/logging/test/logging_test.dart
@@ -129,9 +129,13 @@
expect(loggerA.children['b'], same(loggerAB), reason: 'can read Children');
- expect(() {
- loggerAB.children['test'] = Logger('Fake1234');
- }, throwsUnsupportedError, reason: 'Children is read-only');
+ expect(
+ () {
+ loggerAB.children['test'] = Logger('Fake1234');
+ },
+ throwsUnsupportedError,
+ reason: 'Children is read-only',
+ );
});
test('stackTrace gets throw to LogRecord', () {
@@ -424,17 +428,18 @@
root.shout('8');
expect(
- rootMessages,
- equals([
- 'FINEST: 1',
- 'FINER: 2',
- 'FINE: 3',
- 'CONFIG: 4',
- 'INFO: 5',
- 'WARNING: 6',
- 'SEVERE: 7',
- 'SHOUT: 8'
- ]));
+ rootMessages,
+ equals([
+ 'FINEST: 1',
+ 'FINER: 2',
+ 'FINE: 3',
+ 'CONFIG: 4',
+ 'INFO: 5',
+ 'WARNING: 6',
+ 'SEVERE: 7',
+ 'SHOUT: 8',
+ ]),
+ );
});
test('logging methods store exception', () {
@@ -462,25 +467,26 @@
root.shout('8', 'h');
expect(
- rootMessages,
- equals([
- 'FINEST: 1 null',
- 'FINER: 2 null',
- 'FINE: 3 null',
- 'CONFIG: 4 null',
- 'INFO: 5 null',
- 'WARNING: 6 null',
- 'SEVERE: 7 null',
- 'SHOUT: 8 null',
- 'FINEST: 1 a',
- 'FINER: 2 b',
- 'FINE: 3 [c]',
- 'CONFIG: 4 d',
- 'INFO: 5 e',
- 'WARNING: 6 f',
- 'SEVERE: 7 g',
- 'SHOUT: 8 h'
- ]));
+ rootMessages,
+ equals([
+ 'FINEST: 1 null',
+ 'FINER: 2 null',
+ 'FINE: 3 null',
+ 'CONFIG: 4 null',
+ 'INFO: 5 null',
+ 'WARNING: 6 null',
+ 'SEVERE: 7 null',
+ 'SHOUT: 8 null',
+ 'FINEST: 1 a',
+ 'FINER: 2 b',
+ 'FINE: 3 [c]',
+ 'CONFIG: 4 d',
+ 'INFO: 5 e',
+ 'WARNING: 6 f',
+ 'SEVERE: 7 g',
+ 'SHOUT: 8 h',
+ ]),
+ );
});
test('message logging - no hierarchy', () {
@@ -512,19 +518,20 @@
c.shout('10');
expect(
- rootMessages,
- equals([
- // 'INFO: 1' is not loggable
- // 'FINE: 2' is not loggable
- 'SHOUT: 3',
- // 'INFO: 4' is not loggable
- 'SEVERE: 5',
- 'WARNING: 6',
- // 'FINE: 7' is not loggable
- // 'FINE: 8' is not loggable
- 'WARNING: 9',
- 'SHOUT: 10'
- ]));
+ rootMessages,
+ equals([
+ // 'INFO: 1' is not loggable
+ // 'FINE: 2' is not loggable
+ 'SHOUT: 3',
+ // 'INFO: 4' is not loggable
+ 'SEVERE: 5',
+ 'WARNING: 6',
+ // 'FINE: 7' is not loggable
+ // 'FINE: 8' is not loggable
+ 'WARNING: 9',
+ 'SHOUT: 10',
+ ]),
+ );
// no hierarchy means we all hear the same thing.
expect(aMessages, equals(rootMessages));
@@ -563,41 +570,44 @@
c.shout('10');
expect(
- rootMessages,
- equals([
- 'INFO: 1',
- // 'FINE: 2' is not loggable
- 'SHOUT: 3',
- // 'INFO: 4' is not loggable
- 'SEVERE: 5',
- 'WARNING: 6',
- // 'FINE: 7' is not loggable
- // 'FINE: 8' is not loggable
- 'WARNING: 9',
- 'SHOUT: 10'
- ]));
+ rootMessages,
+ equals([
+ 'INFO: 1',
+ // 'FINE: 2' is not loggable
+ 'SHOUT: 3',
+ // 'INFO: 4' is not loggable
+ 'SEVERE: 5',
+ 'WARNING: 6',
+ // 'FINE: 7' is not loggable
+ // 'FINE: 8' is not loggable
+ 'WARNING: 9',
+ 'SHOUT: 10',
+ ]),
+ );
expect(
- aMessages,
- equals([
- // 1,2 and 3 are lower in the hierarchy
- // 'INFO: 4' is not loggable
- 'SEVERE: 5',
- 'WARNING: 6',
- // 'FINE: 7' is not loggable
- // 'FINE: 8' is not loggable
- 'WARNING: 9',
- 'SHOUT: 10'
- ]));
+ aMessages,
+ equals([
+ // 1,2 and 3 are lower in the hierarchy
+ // 'INFO: 4' is not loggable
+ 'SEVERE: 5',
+ 'WARNING: 6',
+ // 'FINE: 7' is not loggable
+ // 'FINE: 8' is not loggable
+ 'WARNING: 9',
+ 'SHOUT: 10',
+ ]),
+ );
expect(
- cMessages,
- equals([
- // 1 - 7 are lower in the hierarchy
- // 'FINE: 8' is not loggable
- 'WARNING: 9',
- 'SHOUT: 10'
- ]));
+ cMessages,
+ equals([
+ // 1 - 7 are lower in the hierarchy
+ // 'FINE: 8' is not loggable
+ 'WARNING: 9',
+ 'SHOUT: 10',
+ ]),
+ );
});
test('message logging - lazy functions', () {
@@ -614,12 +624,7 @@
root.finer(myClosure); // Should not get evaluated.
root.warning(myClosure);
- expect(
- messages,
- equals([
- 'INFO: 1',
- 'WARNING: 2',
- ]));
+ expect(messages, equals(['INFO: 1', 'WARNING: 2']));
});
test('message logging - calls toString', () {
@@ -639,21 +644,22 @@
root.info(object);
expect(
- messages,
- equals([
- 'INFO: 5',
- 'INFO: false',
- 'INFO: [1, 2, 3]',
- 'INFO: 10',
- "INFO: Instance of 'Object'"
- ]));
+ messages,
+ equals([
+ 'INFO: 5',
+ 'INFO: false',
+ 'INFO: [1, 2, 3]',
+ 'INFO: 10',
+ "INFO: Instance of 'Object'",
+ ]),
+ );
expect(objects, [
5,
false,
[1, 2, 3],
10,
- object
+ object,
]);
});
});
diff --git a/pkgs/os_detect/CHANGELOG.md b/pkgs/os_detect/CHANGELOG.md
index e312741..dc3862f 100644
--- a/pkgs/os_detect/CHANGELOG.md
+++ b/pkgs/os_detect/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 2.0.4-wip
+
+- Run `dart format` with the new style.
+
## 2.0.3
- Move to `package:web`.
diff --git a/pkgs/os_detect/bin/os_detect.dart b/pkgs/os_detect/bin/os_detect.dart
index d886a4f..7669177 100644
--- a/pkgs/os_detect/bin/os_detect.dart
+++ b/pkgs/os_detect/bin/os_detect.dart
@@ -9,8 +9,10 @@
void main() {
final knownName = knownOSName();
- print('OS name : ${os_detect.operatingSystem} '
- '${knownName != null ? '($knownName)' : ''}');
+ print(
+ 'OS name : ${os_detect.operatingSystem} '
+ '${knownName != null ? '($knownName)' : ''}',
+ );
print('OS version : ${os_detect.operatingSystemVersion}');
}
diff --git a/pkgs/os_detect/lib/src/os_override.dart b/pkgs/os_detect/lib/src/os_override.dart
index 6f31bfd..50585ba 100644
--- a/pkgs/os_detect/lib/src/os_override.dart
+++ b/pkgs/os_detect/lib/src/os_override.dart
@@ -93,22 +93,23 @@
@pragma('vm:prefer-inline')
OperatingSystem(String id, String version)
: this._(
- id == linuxId
- ? const LinuxOS()
- : id == macOSId
- ? const MacOS()
- : id == windowsId
- ? const WindowsOS()
- : id == androidId
- ? const AndroidOS()
- : id == iOSId
- ? const IOS()
- : id == fuchsiaId
- ? const FuchsiaOS()
- : id == browserId
- ? const BrowserOS()
- : UnknownOS(id),
- version);
+ id == linuxId
+ ? const LinuxOS()
+ : id == macOSId
+ ? const MacOS()
+ : id == windowsId
+ ? const WindowsOS()
+ : id == androidId
+ ? const AndroidOS()
+ : id == iOSId
+ ? const IOS()
+ : id == fuchsiaId
+ ? const FuchsiaOS()
+ : id == browserId
+ ? const BrowserOS()
+ : UnknownOS(id),
+ version,
+ );
/// Used by platforms which know the ID object.
const OperatingSystem._(this._osId, this.version);
@@ -170,7 +171,9 @@
/// This override affects the `operatingSystem` and `version`
/// exported by `package:osid/osid.dart`.
R overrideOperatingSystem<R>(
- OperatingSystem operatingSystem, R Function() body) =>
+ OperatingSystem operatingSystem,
+ R Function() body,
+) =>
runZoned(body, zoneValues: {#_os: operatingSystem});
// Exposes the `OperatingSystem._` constructor to the conditionally imported
diff --git a/pkgs/os_detect/lib/src/osid_html.dart b/pkgs/os_detect/lib/src/osid_html.dart
index ad84a9a..214133d 100644
--- a/pkgs/os_detect/lib/src/osid_html.dart
+++ b/pkgs/os_detect/lib/src/osid_html.dart
@@ -9,5 +9,7 @@
String get _osVersion => window.navigator.appVersion;
-final OperatingSystem platformOS =
- OperatingSystemInternal(const BrowserOS(), _osVersion);
+final OperatingSystem platformOS = OperatingSystemInternal(
+ const BrowserOS(),
+ _osVersion,
+);
diff --git a/pkgs/os_detect/lib/src/osid_io.dart b/pkgs/os_detect/lib/src/osid_io.dart
index 56b45eb..8d0e4a8 100644
--- a/pkgs/os_detect/lib/src/osid_io.dart
+++ b/pkgs/os_detect/lib/src/osid_io.dart
@@ -29,5 +29,6 @@
: null;
final OperatingSystem platformOS = OperatingSystemInternal(
- _osType ?? UnknownOS(Platform.operatingSystem),
- Platform.operatingSystemVersion);
+ _osType ?? UnknownOS(Platform.operatingSystem),
+ Platform.operatingSystemVersion,
+);
diff --git a/pkgs/os_detect/lib/src/osid_unknown.dart b/pkgs/os_detect/lib/src/osid_unknown.dart
index 2e6798e..83c252b 100644
--- a/pkgs/os_detect/lib/src/osid_unknown.dart
+++ b/pkgs/os_detect/lib/src/osid_unknown.dart
@@ -6,24 +6,27 @@
import 'os_override.dart';
@pragma('vm:platform-const')
-const String _os =
- String.fromEnvironment('dart.os.name', defaultValue: 'unknown');
+const String _os = String.fromEnvironment(
+ 'dart.os.name',
+ defaultValue: 'unknown',
+);
const String _osVersion = String.fromEnvironment('dart.os.version');
const OperatingSystem platformOS = OperatingSystemInternal(
- _os == RecognizedOS.linuxId
- ? LinuxOS()
- : _os == RecognizedOS.macOSId
- ? MacOS()
- : _os == RecognizedOS.windowsId
- ? WindowsOS()
- : _os == RecognizedOS.androidId
- ? AndroidOS()
- : _os == RecognizedOS.iOSId
- ? IOS()
- : _os == RecognizedOS.fuchsiaId
- ? FuchsiaOS()
- : _os == RecognizedOS.browserId
- ? BrowserOS()
- : UnknownOS(_os),
- _osVersion);
+ _os == RecognizedOS.linuxId
+ ? LinuxOS()
+ : _os == RecognizedOS.macOSId
+ ? MacOS()
+ : _os == RecognizedOS.windowsId
+ ? WindowsOS()
+ : _os == RecognizedOS.androidId
+ ? AndroidOS()
+ : _os == RecognizedOS.iOSId
+ ? IOS()
+ : _os == RecognizedOS.fuchsiaId
+ ? FuchsiaOS()
+ : _os == RecognizedOS.browserId
+ ? BrowserOS()
+ : UnknownOS(_os),
+ _osVersion,
+);
diff --git a/pkgs/os_detect/pubspec.yaml b/pkgs/os_detect/pubspec.yaml
index 2e2c0c3..e669e5b 100644
--- a/pkgs/os_detect/pubspec.yaml
+++ b/pkgs/os_detect/pubspec.yaml
@@ -1,5 +1,5 @@
name: os_detect
-version: 2.0.3
+version: 2.0.4-wip
description: Platform independent OS detection.
repository: https://github.com/dart-lang/core/tree/main/pkgs/os_detect
issue_tracker: https://github.com/dart-lang/core/issues?q=is%3Aissue+is%3Aopen+label%3Apackage%3Aos_detect
diff --git a/pkgs/path/CHANGELOG.md b/pkgs/path/CHANGELOG.md
index 0216c30..6ba9562 100644
--- a/pkgs/path/CHANGELOG.md
+++ b/pkgs/path/CHANGELOG.md
@@ -6,6 +6,7 @@
Recognize `#` and `?` as ending an authority or path. Remove
queries and fragments when when normalizing, include them
in/as the last segment when splitting.
+- Run `dart format` with the new style.
## 1.9.1
diff --git a/pkgs/path/benchmark/benchmark.dart b/pkgs/path/benchmark/benchmark.dart
index b6647bb..6eac929 100644
--- a/pkgs/path/benchmark/benchmark.dart
+++ b/pkgs/path/benchmark/benchmark.dart
@@ -22,9 +22,7 @@
'/',
'/home/user/dart/sdk/lib/indexed_db/dart2js/indexed_db_dart2js.dart',
],
- p.Style.url: [
- 'https://example.server.org/443643002/path?top=yes#fragment',
- ],
+ p.Style.url: ['https://example.server.org/443643002/path?top=yes#fragment'],
p.Style.windows: [
r'C:\User\me\',
r'\\server\share\my\folders\some\file.data',
diff --git a/pkgs/path/lib/path.dart b/pkgs/path/lib/path.dart
index 40f1ea3..c8e22e2 100644
--- a/pkgs/path/lib/path.dart
+++ b/pkgs/path/lib/path.dart
@@ -118,23 +118,40 @@
/// p.absolute('path', 'to/foo'); // -> '/your/current/dir/path/to/foo'
///
/// Does not [normalize] or [canonicalize] paths.
-String absolute(String part1,
- [String? part2,
- String? part3,
- String? part4,
- String? part5,
- String? part6,
- String? part7,
- String? part8,
- String? part9,
- String? part10,
- String? part11,
- String? part12,
- String? part13,
- String? part14,
- String? part15]) =>
- context.absolute(part1, part2, part3, part4, part5, part6, part7, part8,
- part9, part10, part11, part12, part13, part14, part15);
+String absolute(
+ String part1, [
+ String? part2,
+ String? part3,
+ String? part4,
+ String? part5,
+ String? part6,
+ String? part7,
+ String? part8,
+ String? part9,
+ String? part10,
+ String? part11,
+ String? part12,
+ String? part13,
+ String? part14,
+ String? part15,
+]) =>
+ context.absolute(
+ part1,
+ part2,
+ part3,
+ part4,
+ part5,
+ part6,
+ part7,
+ part8,
+ part9,
+ part10,
+ part11,
+ part12,
+ part13,
+ part14,
+ part15,
+ );
/// Gets the part of [path] after the last separator.
///
@@ -265,24 +282,42 @@
/// If a part is an absolute path, then anything before that will be ignored:
///
/// p.join('path', '/to', 'foo'); // -> '/to/foo'
-String join(String part1,
- [String? part2,
- String? part3,
- String? part4,
- String? part5,
- String? part6,
- String? part7,
- String? part8,
- String? part9,
- String? part10,
- String? part11,
- String? part12,
- String? part13,
- String? part14,
- String? part15,
- String? part16]) =>
- context.join(part1, part2, part3, part4, part5, part6, part7, part8, part9,
- part10, part11, part12, part13, part14, part15, part16);
+String join(
+ String part1, [
+ String? part2,
+ String? part3,
+ String? part4,
+ String? part5,
+ String? part6,
+ String? part7,
+ String? part8,
+ String? part9,
+ String? part10,
+ String? part11,
+ String? part12,
+ String? part13,
+ String? part14,
+ String? part15,
+ String? part16,
+]) =>
+ context.join(
+ part1,
+ part2,
+ part3,
+ part4,
+ part5,
+ part6,
+ part7,
+ part8,
+ part9,
+ part10,
+ part11,
+ part12,
+ part13,
+ part14,
+ part15,
+ part16,
+ );
/// Joins the given path parts into a single path using the current platform's
/// [separator]. Example:
diff --git a/pkgs/path/lib/src/context.dart b/pkgs/path/lib/src/context.dart
index fef8bb6..562806f 100644
--- a/pkgs/path/lib/src/context.dart
+++ b/pkgs/path/lib/src/context.dart
@@ -37,8 +37,10 @@
if (style == null) {
style = Style.platform;
} else if (style is! InternalStyle) {
- throw ArgumentError('Only styles defined by the path package are '
- 'allowed.');
+ throw ArgumentError(
+ 'Only styles defined by the path package are '
+ 'allowed.',
+ );
}
return Context._(style as InternalStyle, current);
@@ -74,21 +76,23 @@
///
/// If [current] isn't absolute, this won't return an absolute path. Does not
/// [normalize] or [canonicalize] paths.
- String absolute(String part1,
- [String? part2,
- String? part3,
- String? part4,
- String? part5,
- String? part6,
- String? part7,
- String? part8,
- String? part9,
- String? part10,
- String? part11,
- String? part12,
- String? part13,
- String? part14,
- String? part15]) {
+ String absolute(
+ String part1, [
+ String? part2,
+ String? part3,
+ String? part4,
+ String? part5,
+ String? part6,
+ String? part7,
+ String? part8,
+ String? part9,
+ String? part10,
+ String? part11,
+ String? part12,
+ String? part13,
+ String? part14,
+ String? part15,
+ ]) {
_validateArgList('absolute', [
part1,
part2,
@@ -104,7 +108,7 @@
part12,
part13,
part14,
- part15
+ part15,
]);
// If there's a single absolute path, just return it. This is a lot faster
@@ -113,8 +117,24 @@
return part1;
}
- return join(current, part1, part2, part3, part4, part5, part6, part7, part8,
- part9, part10, part11, part12, part13, part14, part15);
+ return join(
+ current,
+ part1,
+ part2,
+ part3,
+ part4,
+ part5,
+ part6,
+ part7,
+ part8,
+ part9,
+ part10,
+ part11,
+ part12,
+ part13,
+ part14,
+ part15,
+ );
}
/// Gets the part of [path] after the last separator on the context's
@@ -245,22 +265,24 @@
///
/// context.join('path', '/to', 'foo'); // -> '/to/foo'
///
- String join(String part1,
- [String? part2,
- String? part3,
- String? part4,
- String? part5,
- String? part6,
- String? part7,
- String? part8,
- String? part9,
- String? part10,
- String? part11,
- String? part12,
- String? part13,
- String? part14,
- String? part15,
- String? part16]) {
+ String join(
+ String part1, [
+ String? part2,
+ String? part3,
+ String? part4,
+ String? part5,
+ String? part6,
+ String? part7,
+ String? part8,
+ String? part9,
+ String? part10,
+ String? part11,
+ String? part12,
+ String? part13,
+ String? part14,
+ String? part15,
+ String? part16,
+ ]) {
final parts = <String?>[
part1,
part2,
@@ -308,8 +330,10 @@
// replaces the path after it.
final parsed = _parse(part);
final path = buffer.toString();
- parsed.root =
- path.substring(0, style.rootLength(path, withDrive: true));
+ parsed.root = path.substring(
+ 0,
+ style.rootLength(path, withDrive: true),
+ );
if (style.needsSeparator(parsed.root!)) {
parsed.separators[0] = style.separator;
}
@@ -574,8 +598,10 @@
}
pathParsed.parts.insertAll(0, List.filled(fromParsed.parts.length, '..'));
pathParsed.separators[0] = '';
- pathParsed.separators
- .insertAll(1, List.filled(fromParsed.parts.length, style.separator));
+ pathParsed.separators.insertAll(
+ 1,
+ List.filled(fromParsed.parts.length, style.separator),
+ );
// Corner case: the paths completely collapsed.
if (pathParsed.parts.isEmpty) return '.';
@@ -1152,10 +1178,12 @@
// Show the arguments.
final message = StringBuffer();
message.write('$method(');
- message.write(args
- .take(numArgs)
- .map((arg) => arg == null ? 'null' : '"$arg"')
- .join(', '));
+ message.write(
+ args
+ .take(numArgs)
+ .map((arg) => arg == null ? 'null' : '"$arg"')
+ .join(', '),
+ );
message.write('): part ${i - 1} was null, but part $i was not.');
throw ArgumentError(message.toString());
}
diff --git a/pkgs/path/lib/src/parsed_path.dart b/pkgs/path/lib/src/parsed_path.dart
index b8f93fe..e0e6099 100644
--- a/pkgs/path/lib/src/parsed_path.dart
+++ b/pkgs/path/lib/src/parsed_path.dart
@@ -83,7 +83,12 @@
}
ParsedPath._(
- this.style, this.root, this.isRootRelative, this.parts, this.separators);
+ this.style,
+ this.root,
+ this.isRootRelative,
+ this.parts,
+ this.separators,
+ );
String get basename {
final copy = clone();
@@ -144,8 +149,11 @@
// Canonicalize separators.
parts = newParts;
- separators =
- List.filled(newParts.length + 1, style.separator, growable: true);
+ separators = List.filled(
+ newParts.length + 1,
+ style.separator,
+ growable: true,
+ );
final root = this.root;
if (root == null || newParts.isEmpty || !style.needsSeparator(root)) {
@@ -209,11 +217,16 @@
List<String> _splitExtension([int level = 1]) {
if (level <= 0) {
throw RangeError.value(
- level, 'level', "level's value must be greater than 0");
+ level,
+ 'level',
+ "level's value must be greater than 0",
+ );
}
- final file =
- parts.cast<String?>().lastWhere((p) => p != '', orElse: () => null);
+ final file = parts.cast<String?>().lastWhere(
+ (p) => p != '',
+ orElse: () => null,
+ );
if (file == null) return ['', ''];
if (file == '..') return ['..', ''];
@@ -228,5 +241,10 @@
}
ParsedPath clone() => ParsedPath._(
- style, root, isRootRelative, List.from(parts), List.from(separators));
+ style,
+ root,
+ isRootRelative,
+ List.from(parts),
+ List.from(separators),
+ );
}
diff --git a/pkgs/path/lib/src/path_map.dart b/pkgs/path/lib/src/path_map.dart
index 50f4d7e..08abc18 100644
--- a/pkgs/path/lib/src/path_map.dart
+++ b/pkgs/path/lib/src/path_map.dart
@@ -27,12 +27,13 @@
static Map<String?, V> _create<V>(p.Context? context) {
context ??= p.context;
return LinkedHashMap(
- equals: (path1, path2) {
- if (path1 == null) return path2 == null;
- if (path2 == null) return false;
- return context!.equals(path1, path2);
- },
- hashCode: (path) => path == null ? 0 : context!.hash(path),
- isValidKey: (path) => path is String || path == null);
+ equals: (path1, path2) {
+ if (path1 == null) return path2 == null;
+ if (path2 == null) return false;
+ return context!.equals(path1, path2);
+ },
+ hashCode: (path) => path == null ? 0 : context!.hash(path),
+ isValidKey: (path) => path is String || path == null,
+ );
}
}
diff --git a/pkgs/path/lib/src/path_set.dart b/pkgs/path/lib/src/path_set.dart
index 424c8a1..52b78e2 100644
--- a/pkgs/path/lib/src/path_set.dart
+++ b/pkgs/path/lib/src/path_set.dart
@@ -30,13 +30,14 @@
static Set<String?> _create(p.Context? context) {
context ??= p.context;
return LinkedHashSet(
- equals: (path1, path2) {
- if (path1 == null) return path2 == null;
- if (path2 == null) return false;
- return context!.equals(path1, path2);
- },
- hashCode: (path) => path == null ? 0 : context!.hash(path),
- isValidKey: (path) => path is String || path == null);
+ equals: (path1, path2) {
+ if (path1 == null) return path2 == null;
+ if (path2 == null) return false;
+ return context!.equals(path1, path2);
+ },
+ hashCode: (path) => path == null ? 0 : context!.hash(path),
+ isValidKey: (path) => path is String || path == null,
+ );
}
// Normally we'd use DelegatingSetView from the collection package to
diff --git a/pkgs/path/lib/src/style/windows.dart b/pkgs/path/lib/src/style/windows.dart
index b7542c6..14c2d8b 100644
--- a/pkgs/path/lib/src/style/windows.dart
+++ b/pkgs/path/lib/src/style/windows.dart
@@ -119,7 +119,10 @@
}
return Uri(
- scheme: 'file', host: rootParts.first, pathSegments: parsed.parts);
+ scheme: 'file',
+ host: rootParts.first,
+ pathSegments: parsed.parts,
+ );
} else {
// Drive-letter paths become "file:///C:/path/to/file".
@@ -133,8 +136,10 @@
// Get rid of the trailing "\" in "C:\" because the URI constructor will
// add a separator on its own.
- parsed.parts
- .insert(0, parsed.root!.replaceAll('/', '').replaceAll('\\', ''));
+ parsed.parts.insert(
+ 0,
+ parsed.root!.replaceAll('/', '').replaceAll('\\', ''),
+ );
return Uri(scheme: 'file', pathSegments: parsed.parts);
}
diff --git a/pkgs/path/test/browser_test.dart b/pkgs/path/test/browser_test.dart
index e88b0c7..1258376 100644
--- a/pkgs/path/test/browser_test.dart
+++ b/pkgs/path/test/browser_test.dart
@@ -13,8 +13,10 @@
group('new Context()', () {
test('uses the window location if root and style are omitted', () {
final context = path.Context();
- expect(context.current,
- Uri.parse(window.location.href).resolve('.').toString());
+ expect(
+ context.current,
+ Uri.parse(window.location.href).resolve('.').toString(),
+ );
});
test('uses "." if root is omitted', () {
@@ -34,6 +36,8 @@
test('current', () {
expect(
- path.current, Uri.parse(window.location.href).resolve('.').toString());
+ path.current,
+ Uri.parse(window.location.href).resolve('.').toString(),
+ );
});
}
diff --git a/pkgs/path/test/io_test.dart b/pkgs/path/test/io_test.dart
index de22caf..e428b89 100644
--- a/pkgs/path/test/io_test.dart
+++ b/pkgs/path/test/io_test.dart
@@ -41,26 +41,29 @@
expect(path.current, io.Directory.current.path);
});
- test('uses the previous working directory if deleted', () {
- final dir = io.Directory.current.path;
- try {
- final temp = io.Directory.systemTemp.createTempSync('path_test');
- final tempPath = temp.resolveSymbolicLinksSync();
- io.Directory.current = temp;
+ test(
+ 'uses the previous working directory if deleted',
+ () {
+ final dir = io.Directory.current.path;
+ try {
+ final temp = io.Directory.systemTemp.createTempSync('path_test');
+ final tempPath = temp.resolveSymbolicLinksSync();
+ io.Directory.current = temp;
- // Call "current" once so that it can be cached.
- expect(path.normalize(path.absolute(path.current)), equals(tempPath));
+ // Call "current" once so that it can be cached.
+ expect(path.normalize(path.absolute(path.current)), equals(tempPath));
- temp.deleteSync();
+ temp.deleteSync();
- // Even though the directory no longer exists, no exception is thrown.
- expect(path.normalize(path.absolute(path.current)), equals(tempPath));
- } finally {
- io.Directory.current = dir;
- }
- },
- //TODO: Figure out why this is failing on windows and fix!
- skip: io.Platform.isWindows ? 'Untriaged failure on Windows' : false);
+ // Even though the directory no longer exists, no exception is thrown.
+ expect(path.normalize(path.absolute(path.current)), equals(tempPath));
+ } finally {
+ io.Directory.current = dir;
+ }
+ },
+ //TODO: Figure out why this is failing on windows and fix!
+ skip: io.Platform.isWindows ? 'Untriaged failure on Windows' : false,
+ );
});
test('registers changes to the working directory', () {
@@ -68,13 +71,19 @@
try {
expect(path.absolute('foo/bar'), equals(path.join(dir, 'foo/bar')));
expect(
- path.absolute('foo/bar'), equals(path.context.join(dir, 'foo/bar')));
+ path.absolute('foo/bar'),
+ equals(path.context.join(dir, 'foo/bar')),
+ );
io.Directory.current = path.dirname(dir);
- expect(path.normalize(path.absolute('foo/bar')),
- equals(path.normalize(path.join(dir, '../foo/bar'))));
- expect(path.normalize(path.absolute('foo/bar')),
- equals(path.normalize(path.context.join(dir, '../foo/bar'))));
+ expect(
+ path.normalize(path.absolute('foo/bar')),
+ equals(path.normalize(path.join(dir, '../foo/bar'))),
+ );
+ expect(
+ path.normalize(path.absolute('foo/bar')),
+ equals(path.normalize(path.context.join(dir, '../foo/bar'))),
+ );
} finally {
io.Directory.current = dir;
}
@@ -83,23 +92,32 @@
// Regression test for #35. This tests against the *actual* working directory
// rather than just a custom context because we do some processing in
// [path.current] that has clobbered the root in the past.
- test('absolute works on root working directory', () {
- final dir = path.current;
- try {
- io.Directory.current = path.rootPrefix(path.current);
+ test(
+ 'absolute works on root working directory',
+ () {
+ final dir = path.current;
+ try {
+ io.Directory.current = path.rootPrefix(path.current);
- expect(path.relative(path.absolute('foo/bar'), from: path.current),
- path.relative(path.absolute('foo/bar')));
+ expect(
+ path.relative(path.absolute('foo/bar'), from: path.current),
+ path.relative(path.absolute('foo/bar')),
+ );
- expect(path.normalize(path.absolute('foo/bar')),
- equals(path.normalize(path.join(path.current, '../foo/bar'))));
+ expect(
+ path.normalize(path.absolute('foo/bar')),
+ equals(path.normalize(path.join(path.current, '../foo/bar'))),
+ );
- expect(path.normalize(path.absolute('foo/bar')),
- equals(path.normalize(path.join(path.current, '../foo/bar'))));
- } finally {
- io.Directory.current = dir;
- }
- },
- //TODO(kevmoo): figure out why this is failing on windows and fix!
- skip: io.Platform.isWindows ? 'Untriaged failure on Windows' : null);
+ expect(
+ path.normalize(path.absolute('foo/bar')),
+ equals(path.normalize(path.join(path.current, '../foo/bar'))),
+ );
+ } finally {
+ io.Directory.current = dir;
+ }
+ },
+ //TODO(kevmoo): figure out why this is failing on windows and fix!
+ skip: io.Platform.isWindows ? 'Untriaged failure on Windows' : null,
+ );
}
diff --git a/pkgs/path/test/posix_test.dart b/pkgs/path/test/posix_test.dart
index 121b4e3..4c82b67 100644
--- a/pkgs/path/test/posix_test.dart
+++ b/pkgs/path/test/posix_test.dart
@@ -150,35 +150,117 @@
expect(context.join('a', 'b', 'c', 'd', 'e'), 'a/b/c/d/e');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f'), 'a/b/c/d/e/f');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g'), 'a/b/c/d/e/f/g');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- 'a/b/c/d/e/f/g/h');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- 'a/b/c/d/e/f/g/h/i');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- 'a/b/c/d/e/f/g/h/i/j');
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- 'a/b/c/d/e/f/g/h/i/j/k');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ 'a/b/c/d/e/f/g/h',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- 'a/b/c/d/e/f/g/h/i/j/k/l');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ 'a/b/c/d/e/f/g/h/i',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ 'a/b/c/d/e/f/g/h/i/j',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ 'a/b/c/d/e/f/g/h/i/j/k',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o', 'p'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p',
+ );
});
test('does not add separator if a part ends in one', () {
@@ -212,8 +294,10 @@
test('join does not modify internal ., .., or trailing separators', () {
expect(context.join('a/', 'b/c/'), 'a/b/c/');
- expect(context.join('a/b/./c/..//', 'd/.././..//e/f//'),
- 'a/b/./c/..//d/.././..//e/f//');
+ expect(
+ context.join('a/b/./c/..//', 'd/.././..//e/f//'),
+ 'a/b/./c/..//d/.././..//e/f//',
+ );
expect(context.join('a/b', 'c/../../../..'), 'a/b/c/../../../..');
expect(context.join('a', 'b${context.separator}'), 'a/b/');
});
@@ -222,26 +306,27 @@
group('joinAll', () {
test('allows more than sixteen parts', () {
expect(
- context.joinAll([
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- 'g',
- 'h',
- 'i',
- 'j',
- 'k',
- 'l',
- 'm',
- 'n',
- 'o',
- 'p',
- 'q'
- ]),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q');
+ context.joinAll([
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ 'q',
+ ]),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q',
+ );
});
test('does not add separator if a part ends in one', () {
@@ -265,8 +350,10 @@
expect(context.split('foo'), equals(['foo']));
expect(context.split('foo/bar.txt'), equals(['foo', 'bar.txt']));
expect(context.split('foo/bar/baz'), equals(['foo', 'bar', 'baz']));
- expect(context.split('foo/../bar/./baz'),
- equals(['foo', '..', 'bar', '.', 'baz']));
+ expect(
+ context.split('foo/../bar/./baz'),
+ equals(['foo', '..', 'bar', '.', 'baz']),
+ );
expect(context.split('foo//bar///baz'), equals(['foo', 'bar', 'baz']));
expect(context.split('foo/\\/baz'), equals(['foo', '\\', 'baz']));
expect(context.split('.'), equals(['.']));
@@ -292,8 +379,10 @@
expect(context.normalize('C:/'), 'C:');
expect(context.normalize(r'C:\'), r'C:\');
expect(context.normalize(r'\\'), r'\\');
- expect(context.normalize('a/./\xc5\u0bf8-;\u{1f085}\u{00}/c/d/../'),
- 'a/\xc5\u0bf8-;\u{1f085}\u{00}/c');
+ expect(
+ context.normalize('a/./\xc5\u0bf8-;\u{1f085}\u{00}/c/d/../'),
+ 'a/\xc5\u0bf8-;\u{1f085}\u{00}/c',
+ );
});
test('collapses redundant separators', () {
@@ -445,8 +534,10 @@
test('with a root parameter', () {
expect(context.relative('/foo/bar/baz', from: '/foo/bar'), equals('baz'));
expect(context.relative('..', from: '/foo/bar'), equals('../../root'));
- expect(context.relative('/foo/bar/baz', from: 'foo/bar'),
- equals('../../../../foo/bar/baz'));
+ expect(
+ context.relative('/foo/bar/baz', from: 'foo/bar'),
+ equals('../../../../foo/bar/baz'),
+ );
expect(context.relative('..', from: 'foo/bar'), equals('../../..'));
});
@@ -455,7 +546,9 @@
expect(r.relative('/foo/bar/baz', from: '/foo/bar'), equals('baz'));
expect(() => r.relative('..', from: '/foo/bar'), throwsPathException);
expect(
- r.relative('/foo/bar/baz', from: 'foo/bar'), equals('/foo/bar/baz'));
+ r.relative('/foo/bar/baz', from: 'foo/bar'),
+ equals('/foo/bar/baz'),
+ );
expect(r.relative('..', from: 'foo/bar'), equals('../../..'));
});
@@ -545,36 +638,104 @@
expect(context.absolute('a', 'b', 'c'), '/root/path/a/b/c');
expect(context.absolute('a', 'b', 'c', 'd'), '/root/path/a/b/c/d');
expect(context.absolute('a', 'b', 'c', 'd', 'e'), '/root/path/a/b/c/d/e');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
- '/root/path/a/b/c/d/e/f');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
- '/root/path/a/b/c/d/e/f/g');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- '/root/path/a/b/c/d/e/f/g/h');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- '/root/path/a/b/c/d/e/f/g/h/i');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- '/root/path/a/b/c/d/e/f/g/h/i/j');
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- '/root/path/a/b/c/d/e/f/g/h/i/j/k');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
+ '/root/path/a/b/c/d/e/f',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- '/root/path/a/b/c/d/e/f/g/h/i/j/k/l');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
+ '/root/path/a/b/c/d/e/f/g',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ '/root/path/a/b/c/d/e/f/g/h',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n'),
- '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ '/root/path/a/b/c/d/e/f/g/h/i',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n', 'o'),
- '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ '/root/path/a/b/c/d/e/f/g/h/i/j',
+ );
+ expect(
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ '/root/path/a/b/c/d/e/f/g/h/i/j/k',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ '/root/path/a/b/c/d/e/f/g/h/i/j/k/l',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ '/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o',
+ );
});
test('does not add separator if a part ends in one', () {
@@ -585,7 +746,9 @@
test('ignores parts before an absolute path', () {
expect(context.absolute('a', '/b', '/c', 'd'), '/c/d');
expect(
- context.absolute('a', r'c:\b', 'c', 'd'), r'/root/path/a/c:\b/c/d');
+ context.absolute('a', r'c:\b', 'c', 'd'),
+ r'/root/path/a/c:\b/c/d',
+ );
expect(context.absolute('a', r'\\b', 'c', 'd'), r'/root/path/a/\\b/c/d');
});
});
@@ -632,17 +795,25 @@
test('with a URI', () {
expect(context.fromUri(Uri.parse('file:///path/to/foo')), '/path/to/foo');
expect(
- context.fromUri(Uri.parse('file:///path/to/foo/')), '/path/to/foo/');
+ context.fromUri(Uri.parse('file:///path/to/foo/')),
+ '/path/to/foo/',
+ );
expect(context.fromUri(Uri.parse('file:///')), '/');
expect(context.fromUri(Uri.parse('foo/bar')), 'foo/bar');
expect(context.fromUri(Uri.parse('/path/to/foo')), '/path/to/foo');
expect(context.fromUri(Uri.parse('///path/to/foo')), '/path/to/foo');
- expect(context.fromUri(Uri.parse('file:///path/to/foo%23bar')),
- '/path/to/foo#bar');
- expect(context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
- r'_{_}_`_^_ _"_%_');
- expect(() => context.fromUri(Uri.parse('https://dart.dev')),
- throwsArgumentError);
+ expect(
+ context.fromUri(Uri.parse('file:///path/to/foo%23bar')),
+ '/path/to/foo#bar',
+ );
+ expect(
+ context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
+ r'_{_}_`_^_ _"_%_',
+ );
+ expect(
+ () => context.fromUri(Uri.parse('https://dart.dev')),
+ throwsArgumentError,
+ );
});
test('with a string', () {
@@ -656,12 +827,18 @@
expect(context.toUri('path/to/foo/'), Uri.parse('path/to/foo/'));
expect(context.toUri('/'), Uri.parse('file:///'));
expect(context.toUri('foo/bar'), Uri.parse('foo/bar'));
- expect(context.toUri('/path/to/foo#bar'),
- Uri.parse('file:///path/to/foo%23bar'));
- expect(context.toUri(r'/_{_}_`_^_ _"_%_'),
- Uri.parse('file:///_%7B_%7D_%60_%5E_%20_%22_%25_'));
- expect(context.toUri(r'_{_}_`_^_ _"_%_'),
- Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'));
+ expect(
+ context.toUri('/path/to/foo#bar'),
+ Uri.parse('file:///path/to/foo%23bar'),
+ );
+ expect(
+ context.toUri(r'/_{_}_`_^_ _"_%_'),
+ Uri.parse('file:///_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
+ expect(
+ context.toUri(r'_{_}_`_^_ _"_%_'),
+ Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
expect(context.toUri(''), Uri.parse(''));
});
diff --git a/pkgs/path/test/url_test.dart b/pkgs/path/test/url_test.dart
index 1d2a716..8143e48 100644
--- a/pkgs/path/test/url_test.dart
+++ b/pkgs/path/test/url_test.dart
@@ -9,7 +9,9 @@
void main() {
final context = path.Context(
- style: path.Style.url, current: 'https://dart.dev/root/path');
+ style: path.Style.url,
+ current: 'https://dart.dev/root/path',
+ );
test('separator', () {
expect(context.separator, '/');
@@ -254,35 +256,117 @@
expect(context.join('a', 'b', 'c', 'd', 'e'), 'a/b/c/d/e');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f'), 'a/b/c/d/e/f');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g'), 'a/b/c/d/e/f/g');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- 'a/b/c/d/e/f/g/h');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- 'a/b/c/d/e/f/g/h/i');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- 'a/b/c/d/e/f/g/h/i/j');
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- 'a/b/c/d/e/f/g/h/i/j/k');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ 'a/b/c/d/e/f/g/h',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- 'a/b/c/d/e/f/g/h/i/j/k/l');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ 'a/b/c/d/e/f/g/h/i',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ 'a/b/c/d/e/f/g/h/i/j',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ 'a/b/c/d/e/f/g/h/i/j/k',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o', 'p'),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ ),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p',
+ );
for (final absolute in ['a:/', '/a', '//a']) {
expect(context.join('a', absolute), absolute);
@@ -295,29 +379,40 @@
});
test('ignores parts before an absolute path', () {
- expect(context.join('a', 'https://dart.dev', 'b', 'c'),
- 'https://dart.dev/b/c');
+ expect(
+ context.join('a', 'https://dart.dev', 'b', 'c'),
+ 'https://dart.dev/b/c',
+ );
expect(context.join('a', 'file://', 'b', 'c'), 'file:///b/c');
expect(context.join('a', '/', 'b', 'c'), '/b/c');
- expect(context.join('a', '/b', 'https://dart.dev/c', 'd'),
- 'https://dart.dev/c/d');
expect(
- context.join('a', 'http://google.com/b', 'https://dart.dev/c', 'd'),
- 'https://dart.dev/c/d');
+ context.join('a', '/b', 'https://dart.dev/c', 'd'),
+ 'https://dart.dev/c/d',
+ );
+ expect(
+ context.join('a', 'http://google.com/b', 'https://dart.dev/c', 'd'),
+ 'https://dart.dev/c/d',
+ );
expect(context.join('a', '/b', '/c', 'd'), '/c/d');
expect(context.join('a', r'c:\b', 'c', 'd'), r'c:\b/c/d');
- expect(context.join('a', 'package:foo/bar', 'c', 'd'),
- r'package:foo/bar/c/d');
+ expect(
+ context.join('a', 'package:foo/bar', 'c', 'd'),
+ r'package:foo/bar/c/d',
+ );
expect(context.join('a', r'\\b', 'c', 'd'), r'a/\\b/c/d');
});
test('preserves roots before a root-relative path', () {
- expect(context.join('https://dart.dev', 'a', '/b', 'c'),
- 'https://dart.dev/b/c');
+ expect(
+ context.join('https://dart.dev', 'a', '/b', 'c'),
+ 'https://dart.dev/b/c',
+ );
expect(context.join('file://', 'a', '/b', 'c'), 'file:///b/c');
expect(context.join('file://', 'a', '/b', 'c', '/d'), 'file:///d');
- expect(context.join('package:foo/bar.dart', '/baz.dart'),
- 'package:foo/baz.dart');
+ expect(
+ context.join('package:foo/bar.dart', '/baz.dart'),
+ 'package:foo/baz.dart',
+ );
});
test('ignores trailing nulls', () {
@@ -339,92 +434,126 @@
test('does not modify internal ., .., or trailing separators', () {
expect(context.join('a/', 'b/c/'), 'a/b/c/');
- expect(context.join('a/b/./c/..//', 'd/.././..//e/f//'),
- 'a/b/./c/..//d/.././..//e/f//');
+ expect(
+ context.join('a/b/./c/..//', 'd/.././..//e/f//'),
+ 'a/b/./c/..//d/.././..//e/f//',
+ );
expect(context.join('a/b', 'c/../../../..'), 'a/b/c/../../../..');
expect(context.join('a', 'b${context.separator}'), 'a/b/');
});
test('treats drive letters as part of the root for file: URLs', () {
expect(
- context.join('file:///c:/foo/bar', '/baz/qux'), 'file:///c:/baz/qux');
+ context.join('file:///c:/foo/bar', '/baz/qux'),
+ 'file:///c:/baz/qux',
+ );
expect(
- context.join('file:///D:/foo/bar', '/baz/qux'), 'file:///D:/baz/qux');
+ context.join('file:///D:/foo/bar', '/baz/qux'),
+ 'file:///D:/baz/qux',
+ );
expect(context.join('file:///c:/', '/baz/qux'), 'file:///c:/baz/qux');
expect(context.join('file:///c:', '/baz/qux'), 'file:///c:/baz/qux');
- expect(context.join('file://host/c:/foo/bar', '/baz/qux'),
- 'file://host/c:/baz/qux');
+ expect(
+ context.join('file://host/c:/foo/bar', '/baz/qux'),
+ 'file://host/c:/baz/qux',
+ );
});
test(
'treats drive letters as part of the root for file: URLs '
'with encoded colons', () {
- expect(context.join('file:///c%3A/foo/bar', '/baz/qux'),
- 'file:///c%3A/baz/qux');
- expect(context.join('file:///D%3A/foo/bar', '/baz/qux'),
- 'file:///D%3A/baz/qux');
+ expect(
+ context.join('file:///c%3A/foo/bar', '/baz/qux'),
+ 'file:///c%3A/baz/qux',
+ );
+ expect(
+ context.join('file:///D%3A/foo/bar', '/baz/qux'),
+ 'file:///D%3A/baz/qux',
+ );
expect(context.join('file:///c%3A/', '/baz/qux'), 'file:///c%3A/baz/qux');
expect(context.join('file:///c%3A', '/baz/qux'), 'file:///c%3A/baz/qux');
- expect(context.join('file://host/c%3A/foo/bar', '/baz/qux'),
- 'file://host/c%3A/baz/qux');
+ expect(
+ context.join('file://host/c%3A/foo/bar', '/baz/qux'),
+ 'file://host/c%3A/baz/qux',
+ );
});
test('treats drive letters as normal components for non-file: URLs', () {
- expect(context.join('http://foo.com/c:/foo/bar', '/baz/qux'),
- 'http://foo.com/baz/qux');
- expect(context.join('misfile:///c:/foo/bar', '/baz/qux'),
- 'misfile:///baz/qux');
expect(
- context.join('filer:///c:/foo/bar', '/baz/qux'), 'filer:///baz/qux');
+ context.join('http://foo.com/c:/foo/bar', '/baz/qux'),
+ 'http://foo.com/baz/qux',
+ );
+ expect(
+ context.join('misfile:///c:/foo/bar', '/baz/qux'),
+ 'misfile:///baz/qux',
+ );
+ expect(
+ context.join('filer:///c:/foo/bar', '/baz/qux'),
+ 'filer:///baz/qux',
+ );
});
});
group('joinAll', () {
test('allows more than sixteen parts', () {
expect(
- context.joinAll([
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- 'g',
- 'h',
- 'i',
- 'j',
- 'k',
- 'l',
- 'm',
- 'n',
- 'o',
- 'p',
- 'q'
- ]),
- 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q');
+ context.joinAll([
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ 'q',
+ ]),
+ 'a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q',
+ );
});
test('ignores parts before an absolute path', () {
- expect(context.joinAll(['a', 'https://dart.dev', 'b', 'c']),
- 'https://dart.dev/b/c');
+ expect(
+ context.joinAll(['a', 'https://dart.dev', 'b', 'c']),
+ 'https://dart.dev/b/c',
+ );
expect(context.joinAll(['a', 'file://', 'b', 'c']), 'file:///b/c');
expect(context.joinAll(['a', '/', 'b', 'c']), '/b/c');
- expect(context.joinAll(['a', '/b', 'https://dart.dev/c', 'd']),
- 'https://dart.dev/c/d');
expect(
- context
- .joinAll(['a', 'http://google.com/b', 'https://dart.dev/c', 'd']),
- 'https://dart.dev/c/d');
+ context.joinAll(['a', '/b', 'https://dart.dev/c', 'd']),
+ 'https://dart.dev/c/d',
+ );
+ expect(
+ context.joinAll([
+ 'a',
+ 'http://google.com/b',
+ 'https://dart.dev/c',
+ 'd',
+ ]),
+ 'https://dart.dev/c/d',
+ );
expect(context.joinAll(['a', '/b', '/c', 'd']), '/c/d');
expect(context.joinAll(['a', r'c:\b', 'c', 'd']), r'c:\b/c/d');
- expect(context.joinAll(['a', 'package:foo/bar', 'c', 'd']),
- r'package:foo/bar/c/d');
+ expect(
+ context.joinAll(['a', 'package:foo/bar', 'c', 'd']),
+ r'package:foo/bar/c/d',
+ );
expect(context.joinAll(['a', r'\\b', 'c', 'd']), r'a/\\b/c/d');
});
test('preserves roots before a root-relative path', () {
- expect(context.joinAll(['https://dart.dev', 'a', '/b', 'c']),
- 'https://dart.dev/b/c');
+ expect(
+ context.joinAll(['https://dart.dev', 'a', '/b', 'c']),
+ 'https://dart.dev/b/c',
+ );
expect(context.joinAll(['file://', 'a', '/b', 'c']), 'file:///b/c');
expect(context.joinAll(['file://', 'a', '/b', 'c', '/d']), 'file:///d');
});
@@ -438,8 +567,10 @@
expect(context.split('foo'), equals(['foo']));
expect(context.split('foo/bar.txt'), equals(['foo', 'bar.txt']));
expect(context.split('foo/bar/baz'), equals(['foo', 'bar', 'baz']));
- expect(context.split('foo/../bar/./baz'),
- equals(['foo', '..', 'bar', '.', 'baz']));
+ expect(
+ context.split('foo/../bar/./baz'),
+ equals(['foo', '..', 'bar', '.', 'baz']),
+ );
expect(context.split('foo//bar///baz'), equals(['foo', 'bar', 'baz']));
expect(context.split('foo/\\/baz'), equals(['foo', '\\', 'baz']));
expect(context.split('.'), equals(['.']));
@@ -450,10 +581,14 @@
});
test('includes the root for absolute paths', () {
- expect(context.split('https://dart.dev/foo/bar/baz'),
- equals(['https://dart.dev', 'foo', 'bar', 'baz']));
- expect(context.split('file:///foo/bar/baz'),
- equals(['file://', 'foo', 'bar', 'baz']));
+ expect(
+ context.split('https://dart.dev/foo/bar/baz'),
+ equals(['https://dart.dev', 'foo', 'bar', 'baz']),
+ );
+ expect(
+ context.split('file:///foo/bar/baz'),
+ equals(['file://', 'foo', 'bar', 'baz']),
+ );
expect(context.split('/foo/bar/baz'), equals(['/', 'foo', 'bar', 'baz']));
expect(context.split('https://dart.dev/'), equals(['https://dart.dev']));
expect(context.split('https://dart.dev'), equals(['https://dart.dev']));
@@ -468,14 +603,22 @@
});
test('includes all queries and fragments in last segment', () {
- expect(context.split('https://dart.dev/foo/bar/baz#42/x'),
- equals(['https://dart.dev', 'foo', 'bar', 'baz#42/x']));
- expect(context.split('file:///foo/bar/baz?42/x'),
- equals(['file://', 'foo', 'bar', 'baz?42/x']));
- expect(context.split('https://dart.dev/foo/bar/baz/#42/x'),
- equals(['https://dart.dev', 'foo', 'bar', 'baz', '#42/x']));
- expect(context.split('file:///foo/bar/baz/?42/x'),
- equals(['file://', 'foo', 'bar', 'baz', '?42/x']));
+ expect(
+ context.split('https://dart.dev/foo/bar/baz#42/x'),
+ equals(['https://dart.dev', 'foo', 'bar', 'baz#42/x']),
+ );
+ expect(
+ context.split('file:///foo/bar/baz?42/x'),
+ equals(['file://', 'foo', 'bar', 'baz?42/x']),
+ );
+ expect(
+ context.split('https://dart.dev/foo/bar/baz/#42/x'),
+ equals(['https://dart.dev', 'foo', 'bar', 'baz', '#42/x']),
+ );
+ expect(
+ context.split('file:///foo/bar/baz/?42/x'),
+ equals(['file://', 'foo', 'bar', 'baz', '?42/x']),
+ );
});
group('normalize', () {
@@ -493,8 +636,10 @@
expect(context.normalize('C:/'), 'C:');
expect(context.normalize(r'C:\'), r'C:\');
expect(context.normalize(r'\\'), r'\\');
- expect(context.normalize('a/./\xc5\u0bf8-;\u{1f085}\u{00}/c/d/../'),
- 'a/\xc5\u0bf8-;\u{1f085}\u{00}/c');
+ expect(
+ context.normalize('a/./\xc5\u0bf8-;\u{1f085}\u{00}/c/d/../'),
+ 'a/\xc5\u0bf8-;\u{1f085}\u{00}/c',
+ );
expect(context.normalize(r'a#b'), r'a');
expect(context.normalize(r'a/b#c/d'), r'a/b');
expect(context.normalize(r'a?b'), r'a');
@@ -535,11 +680,15 @@
expect(context.normalize('file:///..'), 'file://');
expect(context.normalize('/..'), '/');
expect(
- context.normalize('https://dart.dev/../../..'), 'https://dart.dev');
+ context.normalize('https://dart.dev/../../..'),
+ 'https://dart.dev',
+ );
expect(context.normalize('file:///../../..'), 'file://');
expect(context.normalize('/../../..'), '/');
- expect(context.normalize('https://dart.dev/../../../a'),
- 'https://dart.dev/a');
+ expect(
+ context.normalize('https://dart.dev/../../../a'),
+ 'https://dart.dev/a',
+ );
expect(context.normalize('file:///../../../a'), 'file:///a');
expect(context.normalize('/../../../a'), '/a');
expect(context.normalize('c:/..'), 'c:');
@@ -560,14 +709,22 @@
expect(context.normalize('r/a/../b#c/.././/d'), 'r/b');
expect(context.normalize('scheme:r/a/../b?c/.././/d'), 'scheme:r/b');
expect(context.normalize('scheme:r/a/../b#c/.././/d'), 'scheme:r/b');
- expect(context.normalize('scheme://auth/r/a/../b?c/.././/d'),
- 'scheme://auth/r/b');
- expect(context.normalize('scheme://auth/r/a/../b#c/.././/d'),
- 'scheme://auth/r/b');
expect(
- context.normalize('file:///c:/r/a/../b?c/.././/d'), 'file:///c:/r/b');
+ context.normalize('scheme://auth/r/a/../b?c/.././/d'),
+ 'scheme://auth/r/b',
+ );
expect(
- context.normalize('file:///c:/r/a/../b#c/.././/d'), 'file:///c:/r/b');
+ context.normalize('scheme://auth/r/a/../b#c/.././/d'),
+ 'scheme://auth/r/b',
+ );
+ expect(
+ context.normalize('file:///c:/r/a/../b?c/.././/d'),
+ 'file:///c:/r/b',
+ );
+ expect(
+ context.normalize('file:///c:/r/a/../b#c/.././/d'),
+ 'file:///c:/r/b',
+ );
});
test('does not walk before root on absolute paths', () {
@@ -605,44 +762,70 @@
group('when canonicalizing', () {
test('adds scheme', () {
expect(context.canonicalize('.'), 'https://dart.dev/root/path');
- expect(context.canonicalize('foo/bar'),
- 'https://dart.dev/root/path/foo/bar');
+ expect(
+ context.canonicalize('foo/bar'),
+ 'https://dart.dev/root/path/foo/bar',
+ );
expect(context.canonicalize('FoO'), 'https://dart.dev/root/path/FoO');
expect(context.canonicalize('/foo'), 'https://dart.dev/foo');
- expect(context.canonicalize('http://google.com/foo'),
- 'http://google.com/foo');
+ expect(
+ context.canonicalize('http://google.com/foo'),
+ 'http://google.com/foo',
+ );
});
test('eliminates queries and fragments', () {
// Adds scheme and path if relative.
- expect(context.canonicalize('r/a/../b?c/.././/d'),
- 'https://dart.dev/root/path/r/b');
- expect(context.canonicalize('r/a/../b#c/.././/d'),
- 'https://dart.dev/root/path/r/b');
+ expect(
+ context.canonicalize('r/a/../b?c/.././/d'),
+ 'https://dart.dev/root/path/r/b',
+ );
+ expect(
+ context.canonicalize('r/a/../b#c/.././/d'),
+ 'https://dart.dev/root/path/r/b',
+ );
// Adds scheme if root relative.
- expect(context.canonicalize('/r/a/../b?c/.././/d'),
- 'https://dart.dev/r/b');
- expect(context.canonicalize('/r/a/../b#c/.././/d'),
- 'https://dart.dev/r/b');
+ expect(
+ context.canonicalize('/r/a/../b?c/.././/d'),
+ 'https://dart.dev/r/b',
+ );
+ expect(
+ context.canonicalize('/r/a/../b#c/.././/d'),
+ 'https://dart.dev/r/b',
+ );
expect(context.canonicalize('scheme:r/a/../b?c/.././/d'), 'scheme:r/b');
expect(context.canonicalize('scheme:r/a/../b#c/.././/d'), 'scheme:r/b');
- expect(context.canonicalize('scheme://auth/r/a/../b?c/.././/d'),
- 'scheme://auth/r/b');
- expect(context.canonicalize('scheme://auth/r/a/../b#c/.././/d'),
- 'scheme://auth/r/b');
- expect(context.canonicalize('file:///c:/r/a/../b?c/.././/d'),
- 'file:///c:/r/b');
- expect(context.canonicalize('file:///c:/r/a/../b#c/.././/d'),
- 'file:///c:/r/b');
+ expect(
+ context.canonicalize('scheme://auth/r/a/../b?c/.././/d'),
+ 'scheme://auth/r/b',
+ );
+ expect(
+ context.canonicalize('scheme://auth/r/a/../b#c/.././/d'),
+ 'scheme://auth/r/b',
+ );
+ expect(
+ context.canonicalize('file:///c:/r/a/../b?c/.././/d'),
+ 'file:///c:/r/b',
+ );
+ expect(
+ context.canonicalize('file:///c:/r/a/../b#c/.././/d'),
+ 'file:///c:/r/b',
+ );
});
test('case-canonicalizes scheme and authority', () {
- expect(context.canonicalize('HTTPS://EXAMPLE.COM/FILE.EXT'),
- 'https://example.com/FILE.EXT');
expect(
- context.canonicalize('FILE:///C:/FILE.EXT'), 'file:///c:/FILE.EXT');
- expect(context.canonicalize('PACKAGE:FOO//FILE.EXT'),
- 'package:foo/FILE.EXT');
+ context.canonicalize('HTTPS://EXAMPLE.COM/FILE.EXT'),
+ 'https://example.com/FILE.EXT',
+ );
+ expect(
+ context.canonicalize('FILE:///C:/FILE.EXT'),
+ 'file:///c:/FILE.EXT',
+ );
+ expect(
+ context.canonicalize('PACKAGE:FOO//FILE.EXT'),
+ 'package:foo/FILE.EXT',
+ );
});
});
});
@@ -660,7 +843,9 @@
expect(context.relative('https://dart.dev/root/path/a'), 'a');
expect(context.relative('/root/path/a'), 'a');
expect(
- context.relative('https://dart.dev/root/path/a/b.txt'), 'a/b.txt');
+ context.relative('https://dart.dev/root/path/a/b.txt'),
+ 'a/b.txt',
+ );
expect(context.relative('/root/path/a/b.txt'), 'a/b.txt');
expect(context.relative('https://dart.dev/root/a/b.txt'), '../a/b.txt');
expect(context.relative('/root/a/b.txt'), '../a/b.txt');
@@ -672,15 +857,21 @@
expect(context.relative('https://dart.dev/root/path/a'), 'a');
expect(context.relative('/root/path/a'), 'a');
expect(
- context.relative('https://dart.dev/root/path/a/b.txt'), 'a/b.txt');
+ context.relative('https://dart.dev/root/path/a/b.txt'),
+ 'a/b.txt',
+ );
expect(
- context.relative('https://dart.dev/root/path/a/b.txt'), 'a/b.txt');
+ context.relative('https://dart.dev/root/path/a/b.txt'),
+ 'a/b.txt',
+ );
expect(context.relative('https://dart.dev/root/a/b.txt'), '../a/b.txt');
});
test('given absolute path with different hostname/protocol', () {
- expect(context.relative(r'http://google.com/a/b'),
- r'http://google.com/a/b');
+ expect(
+ context.relative(r'http://google.com/a/b'),
+ r'http://google.com/a/b',
+ );
expect(context.relative(r'file:///a/b'), r'file:///a/b');
});
@@ -697,21 +888,30 @@
test('is case-sensitive', () {
expect(
- context.relative('HtTps://dart.dev/root'), 'HtTps://dart.dev/root');
+ context.relative('HtTps://dart.dev/root'),
+ 'HtTps://dart.dev/root',
+ );
expect(
- context.relative('https://DaRt.DeV/root'), 'https://DaRt.DeV/root');
+ context.relative('https://DaRt.DeV/root'),
+ 'https://DaRt.DeV/root',
+ );
expect(context.relative('/RoOt'), '../../RoOt');
expect(context.relative('/rOoT/pAtH/a'), '../../rOoT/pAtH/a');
});
// Regression
test('from root-only path', () {
- expect(context.relative('https://dart.dev', from: 'https://dart.dev'),
- '.');
expect(
- context.relative('https://dart.dev/root/path',
- from: 'https://dart.dev'),
- 'root/path');
+ context.relative('https://dart.dev', from: 'https://dart.dev'),
+ '.',
+ );
+ expect(
+ context.relative(
+ 'https://dart.dev/root/path',
+ from: 'https://dart.dev',
+ ),
+ 'root/path',
+ );
});
});
@@ -772,36 +972,60 @@
test('with a root parameter', () {
expect(context.relative('/foo/bar/baz', from: '/foo/bar'), equals('baz'));
- expect(context.relative('/foo/bar/baz', from: 'https://dart.dev/foo/bar'),
- equals('baz'));
- expect(context.relative('https://dart.dev/foo/bar/baz', from: '/foo/bar'),
- equals('baz'));
expect(
- context.relative('https://dart.dev/foo/bar/baz',
- from: 'file:///foo/bar'),
- equals('https://dart.dev/foo/bar/baz'));
+ context.relative('/foo/bar/baz', from: 'https://dart.dev/foo/bar'),
+ equals('baz'),
+ );
expect(
- context.relative('https://dart.dev/foo/bar/baz',
- from: 'https://dart.dev/foo/bar'),
- equals('baz'));
- expect(context.relative('/foo/bar/baz', from: 'file:///foo/bar'),
- equals('https://dart.dev/foo/bar/baz'));
- expect(context.relative('file:///foo/bar/baz', from: '/foo/bar'),
- equals('file:///foo/bar/baz'));
+ context.relative('https://dart.dev/foo/bar/baz', from: '/foo/bar'),
+ equals('baz'),
+ );
+ expect(
+ context.relative(
+ 'https://dart.dev/foo/bar/baz',
+ from: 'file:///foo/bar',
+ ),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
+ expect(
+ context.relative(
+ 'https://dart.dev/foo/bar/baz',
+ from: 'https://dart.dev/foo/bar',
+ ),
+ equals('baz'),
+ );
+ expect(
+ context.relative('/foo/bar/baz', from: 'file:///foo/bar'),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
+ expect(
+ context.relative('file:///foo/bar/baz', from: '/foo/bar'),
+ equals('file:///foo/bar/baz'),
+ );
expect(context.relative('..', from: '/foo/bar'), equals('../../root'));
- expect(context.relative('..', from: 'https://dart.dev/foo/bar'),
- equals('../../root'));
- expect(context.relative('..', from: 'file:///foo/bar'),
- equals('https://dart.dev/root'));
+ expect(
+ context.relative('..', from: 'https://dart.dev/foo/bar'),
+ equals('../../root'),
+ );
+ expect(
+ context.relative('..', from: 'file:///foo/bar'),
+ equals('https://dart.dev/root'),
+ );
expect(context.relative('..', from: '/foo/bar'), equals('../../root'));
- expect(context.relative('https://dart.dev/foo/bar/baz', from: 'foo/bar'),
- equals('../../../../foo/bar/baz'));
- expect(context.relative('file:///foo/bar/baz', from: 'foo/bar'),
- equals('file:///foo/bar/baz'));
- expect(context.relative('/foo/bar/baz', from: 'foo/bar'),
- equals('../../../../foo/bar/baz'));
+ expect(
+ context.relative('https://dart.dev/foo/bar/baz', from: 'foo/bar'),
+ equals('../../../../foo/bar/baz'),
+ );
+ expect(
+ context.relative('file:///foo/bar/baz', from: 'foo/bar'),
+ equals('file:///foo/bar/baz'),
+ );
+ expect(
+ context.relative('/foo/bar/baz', from: 'foo/bar'),
+ equals('../../../../foo/bar/baz'),
+ );
expect(context.relative('..', from: 'foo/bar'), equals('../../..'));
});
@@ -809,32 +1033,48 @@
test('with a root parameter and a relative root', () {
final r = path.Context(style: path.Style.url, current: 'relative/root');
expect(r.relative('/foo/bar/baz', from: '/foo/bar'), equals('baz'));
- expect(r.relative('/foo/bar/baz', from: 'https://dart.dev/foo/bar'),
- equals('/foo/bar/baz'));
- expect(r.relative('https://dart.dev/foo/bar/baz', from: '/foo/bar'),
- equals('https://dart.dev/foo/bar/baz'));
expect(
- r.relative('https://dart.dev/foo/bar/baz', from: 'file:///foo/bar'),
- equals('https://dart.dev/foo/bar/baz'));
+ r.relative('/foo/bar/baz', from: 'https://dart.dev/foo/bar'),
+ equals('/foo/bar/baz'),
+ );
expect(
- r.relative('https://dart.dev/foo/bar/baz',
- from: 'https://dart.dev/foo/bar'),
- equals('baz'));
+ r.relative('https://dart.dev/foo/bar/baz', from: '/foo/bar'),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
+ expect(
+ r.relative('https://dart.dev/foo/bar/baz', from: 'file:///foo/bar'),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
+ expect(
+ r.relative(
+ 'https://dart.dev/foo/bar/baz',
+ from: 'https://dart.dev/foo/bar',
+ ),
+ equals('baz'),
+ );
- expect(r.relative('https://dart.dev/foo/bar/baz', from: 'foo/bar'),
- equals('https://dart.dev/foo/bar/baz'));
- expect(r.relative('file:///foo/bar/baz', from: 'foo/bar'),
- equals('file:///foo/bar/baz'));
expect(
- r.relative('/foo/bar/baz', from: 'foo/bar'), equals('/foo/bar/baz'));
+ r.relative('https://dart.dev/foo/bar/baz', from: 'foo/bar'),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
+ expect(
+ r.relative('file:///foo/bar/baz', from: 'foo/bar'),
+ equals('file:///foo/bar/baz'),
+ );
+ expect(
+ r.relative('/foo/bar/baz', from: 'foo/bar'),
+ equals('/foo/bar/baz'),
+ );
expect(r.relative('..', from: 'foo/bar'), equals('../../..'));
});
test('from a . root', () {
final r = path.Context(style: path.Style.url, current: '.');
- expect(r.relative('https://dart.dev/foo/bar/baz'),
- equals('https://dart.dev/foo/bar/baz'));
+ expect(
+ r.relative('https://dart.dev/foo/bar/baz'),
+ equals('https://dart.dev/foo/bar/baz'),
+ );
expect(r.relative('file:///foo/bar/baz'), equals('file:///foo/bar/baz'));
expect(r.relative('/foo/bar/baz'), equals('/foo/bar/baz'));
expect(r.relative('foo/bar/baz'), equals('foo/bar/baz'));
@@ -847,18 +1087,25 @@
expect(context.isWithin('foo/bar', 'foo/bar/baz'), isTrue);
expect(context.isWithin('foo/bar', 'foo/baz'), isFalse);
expect(context.isWithin('foo/bar', '../path/foo/bar/baz'), isTrue);
- expect(context.isWithin('https://dart.dev', 'https://dart.dev/foo/bar'),
- isTrue);
expect(
- context.isWithin('https://dart.dev', 'http://psub.dart.dev/foo/bar'),
- isFalse);
+ context.isWithin('https://dart.dev', 'https://dart.dev/foo/bar'),
+ isTrue,
+ );
+ expect(
+ context.isWithin('https://dart.dev', 'http://psub.dart.dev/foo/bar'),
+ isFalse,
+ );
expect(context.isWithin('https://dart.dev', '/foo/bar'), isTrue);
expect(context.isWithin('https://dart.dev/foo', '/foo/bar'), isTrue);
expect(context.isWithin('https://dart.dev/foo', '/bar/baz'), isFalse);
- expect(context.isWithin('baz', 'https://dart.dev/root/path/baz/bang'),
- isTrue);
- expect(context.isWithin('baz', 'https://dart.dev/root/path/bang/baz'),
- isFalse);
+ expect(
+ context.isWithin('baz', 'https://dart.dev/root/path/baz/bang'),
+ isTrue,
+ );
+ expect(
+ context.isWithin('baz', 'https://dart.dev/root/path/bang/baz'),
+ isFalse,
+ );
});
test('complex cases', () {
@@ -872,10 +1119,14 @@
expect(context.isWithin('foo/..bar', 'foo/..bar/baz'), isTrue);
expect(context.isWithin('foo/bar', 'foo/bar/baz/..'), isFalse);
expect(context.isWithin('foo/bar', 'foo/bar/baz/../qux'), isTrue);
- expect(context.isWithin('http://example.org/', 'http://example.com/foo'),
- isFalse);
- expect(context.isWithin('http://example.org/', 'https://dart.dev/foo'),
- isFalse);
+ expect(
+ context.isWithin('http://example.org/', 'http://example.com/foo'),
+ isFalse,
+ );
+ expect(
+ context.isWithin('http://example.org/', 'https://dart.dev/foo'),
+ isFalse,
+ );
});
test('with root-relative paths', () {
@@ -892,7 +1143,9 @@
expect(r.isWithin('.', '../a/b/c'), isFalse);
expect(r.isWithin('.', '../../a/foo/b/c'), isFalse);
expect(
- r.isWithin('https://dart.dev/', 'https://dart.dev/baz/bang'), isTrue);
+ r.isWithin('https://dart.dev/', 'https://dart.dev/baz/bang'),
+ isTrue,
+ );
expect(r.isWithin('.', 'https://dart.dev/baz/bang'), isFalse);
});
});
@@ -948,46 +1201,122 @@
expect(context.absolute('a'), 'https://dart.dev/root/path/a');
expect(context.absolute('a', 'b'), 'https://dart.dev/root/path/a/b');
expect(
- context.absolute('a', 'b', 'c'), 'https://dart.dev/root/path/a/b/c');
- expect(context.absolute('a', 'b', 'c', 'd'),
- 'https://dart.dev/root/path/a/b/c/d');
- expect(context.absolute('a', 'b', 'c', 'd', 'e'),
- 'https://dart.dev/root/path/a/b/c/d/e');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
- 'https://dart.dev/root/path/a/b/c/d/e/f');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j');
+ context.absolute('a', 'b', 'c'),
+ 'https://dart.dev/root/path/a/b/c',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k');
+ context.absolute('a', 'b', 'c', 'd'),
+ 'https://dart.dev/root/path/a/b/c/d',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l');
+ context.absolute('a', 'b', 'c', 'd', 'e'),
+ 'https://dart.dev/root/path/a/b/c/d/e',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n', 'o'),
- 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h',
+ );
+ expect(
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i',
+ );
+ expect(
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j',
+ );
+ expect(
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ 'https://dart.dev/root/path/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o',
+ );
});
test('does not add separator if a part ends in one', () {
- expect(context.absolute('a/', 'b', 'c/', 'd'),
- 'https://dart.dev/root/path/a/b/c/d');
+ expect(
+ context.absolute('a/', 'b', 'c/', 'd'),
+ 'https://dart.dev/root/path/a/b/c/d',
+ );
expect(context.absolute(r'a\', 'b'), r'https://dart.dev/root/path/a\/b');
});
@@ -995,8 +1324,10 @@
expect(context.absolute('a', '/b', '/c', 'd'), 'https://dart.dev/c/d');
expect(context.absolute('a', '/b', 'file:///c', 'd'), 'file:///c/d');
expect(context.absolute('a', r'c:\b', 'c', 'd'), r'c:\b/c/d');
- expect(context.absolute('a', r'\\b', 'c', 'd'),
- r'https://dart.dev/root/path/a/\\b/c/d');
+ expect(
+ context.absolute('a', r'\\b', 'c', 'd'),
+ r'https://dart.dev/root/path/a/\\b/c/d',
+ );
});
});
@@ -1040,60 +1371,90 @@
group('fromUri', () {
test('with a URI', () {
- expect(context.fromUri(Uri.parse('https://dart.dev/path/to/foo')),
- 'https://dart.dev/path/to/foo');
- expect(context.fromUri(Uri.parse('https://dart.dev/path/to/foo/')),
- 'https://dart.dev/path/to/foo/');
- expect(context.fromUri(Uri.parse('file:///path/to/foo')),
- 'file:///path/to/foo');
+ expect(
+ context.fromUri(Uri.parse('https://dart.dev/path/to/foo')),
+ 'https://dart.dev/path/to/foo',
+ );
+ expect(
+ context.fromUri(Uri.parse('https://dart.dev/path/to/foo/')),
+ 'https://dart.dev/path/to/foo/',
+ );
+ expect(
+ context.fromUri(Uri.parse('file:///path/to/foo')),
+ 'file:///path/to/foo',
+ );
expect(context.fromUri(Uri.parse('foo/bar')), 'foo/bar');
- expect(context.fromUri(Uri.parse('https://dart.dev/path/to/foo%23bar')),
- 'https://dart.dev/path/to/foo%23bar');
+ expect(
+ context.fromUri(Uri.parse('https://dart.dev/path/to/foo%23bar')),
+ 'https://dart.dev/path/to/foo%23bar',
+ );
// Since the resulting "path" is also a URL, special characters should
// remain percent-encoded in the result.
- expect(context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
- r'_%7B_%7D_%60_%5E_%20_%22_%25_');
+ expect(
+ context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
+ r'_%7B_%7D_%60_%5E_%20_%22_%25_',
+ );
});
test('with a string', () {
- expect(context.fromUri('https://dart.dev/path/to/foo'),
- 'https://dart.dev/path/to/foo');
+ expect(
+ context.fromUri('https://dart.dev/path/to/foo'),
+ 'https://dart.dev/path/to/foo',
+ );
});
});
test('toUri', () {
- expect(context.toUri('https://dart.dev/path/to/foo'),
- Uri.parse('https://dart.dev/path/to/foo'));
- expect(context.toUri('https://dart.dev/path/to/foo/'),
- Uri.parse('https://dart.dev/path/to/foo/'));
+ expect(
+ context.toUri('https://dart.dev/path/to/foo'),
+ Uri.parse('https://dart.dev/path/to/foo'),
+ );
+ expect(
+ context.toUri('https://dart.dev/path/to/foo/'),
+ Uri.parse('https://dart.dev/path/to/foo/'),
+ );
expect(context.toUri('path/to/foo/'), Uri.parse('path/to/foo/'));
expect(
- context.toUri('file:///path/to/foo'), Uri.parse('file:///path/to/foo'));
+ context.toUri('file:///path/to/foo'),
+ Uri.parse('file:///path/to/foo'),
+ );
expect(context.toUri('foo/bar'), Uri.parse('foo/bar'));
- expect(context.toUri('https://dart.dev/path/to/foo%23bar'),
- Uri.parse('https://dart.dev/path/to/foo%23bar'));
+ expect(
+ context.toUri('https://dart.dev/path/to/foo%23bar'),
+ Uri.parse('https://dart.dev/path/to/foo%23bar'),
+ );
// Since the input path is also a URI, special characters should already
// be percent encoded there too.
- expect(context.toUri(r'http://foo.com/_%7B_%7D_%60_%5E_%20_%22_%25_'),
- Uri.parse('http://foo.com/_%7B_%7D_%60_%5E_%20_%22_%25_'));
- expect(context.toUri(r'_%7B_%7D_%60_%5E_%20_%22_%25_'),
- Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'));
+ expect(
+ context.toUri(r'http://foo.com/_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ Uri.parse('http://foo.com/_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
+ expect(
+ context.toUri(r'_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
expect(context.toUri(''), Uri.parse(''));
});
group('prettyUri', () {
test('with a file: URI', () {
- expect(context.prettyUri(Uri.parse('file:///root/path/a/b')),
- 'file:///root/path/a/b');
+ expect(
+ context.prettyUri(Uri.parse('file:///root/path/a/b')),
+ 'file:///root/path/a/b',
+ );
});
test('with an http: URI', () {
expect(context.prettyUri('https://dart.dev/root/path/a/b'), 'a/b');
expect(context.prettyUri('https://dart.dev/root/path/a/../b'), 'b');
- expect(context.prettyUri('https://dart.dev/other/path/a/b'),
- 'https://dart.dev/other/path/a/b');
- expect(context.prettyUri('http://psub.dart.dev/root/path'),
- 'http://psub.dart.dev/root/path');
+ expect(
+ context.prettyUri('https://dart.dev/other/path/a/b'),
+ 'https://dart.dev/other/path/a/b',
+ );
+ expect(
+ context.prettyUri('http://psub.dart.dev/root/path'),
+ 'http://psub.dart.dev/root/path',
+ );
expect(context.prettyUri('https://dart.dev/root/other'), '../other');
});
diff --git a/pkgs/path/test/utils.dart b/pkgs/path/test/utils.dart
index 08d4a52..27d81c8 100644
--- a/pkgs/path/test/utils.dart
+++ b/pkgs/path/test/utils.dart
@@ -9,24 +9,46 @@
final throwsPathException = throwsA(const TypeMatcher<p.PathException>());
void expectEquals(p.Context context, String path1, String path2) {
- expect(context.equals(path1, path2), isTrue,
- reason: 'Expected "$path1" to equal "$path2".');
- expect(context.equals(path2, path1), isTrue,
- reason: 'Expected "$path2" to equal "$path1".');
- expect(context.hash(path1), equals(context.hash(path2)),
- reason: 'Expected "$path1" to hash the same as "$path2".');
+ expect(
+ context.equals(path1, path2),
+ isTrue,
+ reason: 'Expected "$path1" to equal "$path2".',
+ );
+ expect(
+ context.equals(path2, path1),
+ isTrue,
+ reason: 'Expected "$path2" to equal "$path1".',
+ );
+ expect(
+ context.hash(path1),
+ equals(context.hash(path2)),
+ reason: 'Expected "$path1" to hash the same as "$path2".',
+ );
}
-void expectNotEquals(p.Context context, String path1, String path2,
- {bool allowSameHash = false}) {
- expect(context.equals(path1, path2), isFalse,
- reason: 'Expected "$path1" not to equal "$path2".');
- expect(context.equals(path2, path1), isFalse,
- reason: 'Expected "$path2" not to equal "$path1".');
+void expectNotEquals(
+ p.Context context,
+ String path1,
+ String path2, {
+ bool allowSameHash = false,
+}) {
+ expect(
+ context.equals(path1, path2),
+ isFalse,
+ reason: 'Expected "$path1" not to equal "$path2".',
+ );
+ expect(
+ context.equals(path2, path1),
+ isFalse,
+ reason: 'Expected "$path2" not to equal "$path1".',
+ );
// Hash collisions are allowed, but the test author should be explicitly aware
// when they occur.
if (allowSameHash) return;
- expect(context.hash(path1), isNot(equals(context.hash(path2))),
- reason: 'Expected "$path1" not to hash the same as "$path2".');
+ expect(
+ context.hash(path1),
+ isNot(equals(context.hash(path2))),
+ reason: 'Expected "$path1" not to hash the same as "$path2".',
+ );
}
diff --git a/pkgs/path/test/windows_test.dart b/pkgs/path/test/windows_test.dart
index 3808354..3202629 100644
--- a/pkgs/path/test/windows_test.dart
+++ b/pkgs/path/test/windows_test.dart
@@ -9,8 +9,10 @@
import 'utils.dart';
void main() {
- final context =
- path.Context(style: path.Style.windows, current: r'C:\root\path');
+ final context = path.Context(
+ style: path.Style.windows,
+ current: r'C:\root\path',
+ );
test('separator', () {
expect(context.separator, '\\');
@@ -214,35 +216,117 @@
expect(context.join('a', 'b', 'c', 'd', 'e'), r'a\b\c\d\e');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f'), r'a\b\c\d\e\f');
expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g'), r'a\b\c\d\e\f\g');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- r'a\b\c\d\e\f\g\h');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- r'a\b\c\d\e\f\g\h\i');
- expect(context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- r'a\b\c\d\e\f\g\h\i\j');
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- r'a\b\c\d\e\f\g\h\i\j\k');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ r'a\b\c\d\e\f\g\h',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- r'a\b\c\d\e\f\g\h\i\j\k\l');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ r'a\b\c\d\e\f\g\h\i',
+ );
expect(
- context.join(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- r'a\b\c\d\e\f\g\h\i\j\k\l\m');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ r'a\b\c\d\e\f\g\h\i\j',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n'),
- r'a\b\c\d\e\f\g\h\i\j\k\l\m\n');
+ context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ r'a\b\c\d\e\f\g\h\i\j\k',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o'),
- r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ r'a\b\c\d\e\f\g\h\i\j\k\l',
+ );
expect(
- context.join('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
- 'l', 'm', 'n', 'o', 'p'),
- r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p');
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ r'a\b\c\d\e\f\g\h\i\j\k\l\m',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ r'a\b\c\d\e\f\g\h\i\j\k\l\m\n',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o',
+ );
+ expect(
+ context.join(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ ),
+ r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p',
+ );
});
test('does not add separator if a part ends or begins in one', () {
@@ -278,8 +362,10 @@
test('join does not modify internal ., .., or trailing separators', () {
expect(context.join('a/', 'b/c/'), 'a/b/c/');
- expect(context.join(r'a\b\./c\..\\', r'd\..\.\..\\e\f\\'),
- r'a\b\./c\..\\d\..\.\..\\e\f\\');
+ expect(
+ context.join(r'a\b\./c\..\\', r'd\..\.\..\\e\f\\'),
+ r'a\b\./c\..\\d\..\.\..\\e\f\\',
+ );
expect(context.join(r'a\b', r'c\..\..\..\..'), r'a\b\c\..\..\..\..');
expect(context.join(r'a', 'b${context.separator}'), r'a\b\');
});
@@ -288,26 +374,27 @@
group('joinAll', () {
test('allows more than sixteen parts', () {
expect(
- context.joinAll([
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- 'g',
- 'h',
- 'i',
- 'j',
- 'k',
- 'l',
- 'm',
- 'n',
- 'o',
- 'p',
- 'q'
- ]),
- r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q');
+ context.joinAll([
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ 'q',
+ ]),
+ r'a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q',
+ );
});
test('does not add separator if a part ends or begins in one', () {
@@ -333,8 +420,10 @@
expect(context.split('foo'), equals(['foo']));
expect(context.split(r'foo\bar.txt'), equals(['foo', 'bar.txt']));
expect(context.split(r'foo\bar/baz'), equals(['foo', 'bar', 'baz']));
- expect(context.split(r'foo\..\bar\.\baz'),
- equals(['foo', '..', 'bar', '.', 'baz']));
+ expect(
+ context.split(r'foo\..\bar\.\baz'),
+ equals(['foo', '..', 'bar', '.', 'baz']),
+ );
expect(context.split(r'foo\\bar\\\baz'), equals(['foo', 'bar', 'baz']));
expect(context.split(r'foo\/\baz'), equals(['foo', 'baz']));
expect(context.split('.'), equals(['.']));
@@ -344,16 +433,22 @@
});
test('includes the root for absolute paths', () {
- expect(context.split(r'C:\foo\bar\baz'),
- equals([r'C:\', 'foo', 'bar', 'baz']));
+ expect(
+ context.split(r'C:\foo\bar\baz'),
+ equals([r'C:\', 'foo', 'bar', 'baz']),
+ );
expect(context.split(r'C:\\'), equals([r'C:\']));
- expect(context.split(r'\\server\share\foo\bar\baz'),
- equals([r'\\server\share', 'foo', 'bar', 'baz']));
+ expect(
+ context.split(r'\\server\share\foo\bar\baz'),
+ equals([r'\\server\share', 'foo', 'bar', 'baz']),
+ );
expect(context.split(r'\\server\share'), equals([r'\\server\share']));
expect(
- context.split(r'\foo\bar\baz'), equals([r'\', 'foo', 'bar', 'baz']));
+ context.split(r'\foo\bar\baz'),
+ equals([r'\', 'foo', 'bar', 'baz']),
+ );
expect(context.split(r'\'), equals([r'\']));
});
});
@@ -371,8 +466,10 @@
expect(context.normalize('C:/'), r'C:\');
expect(context.normalize(r'C:\'), r'C:\');
expect(context.normalize(r'\\server\share'), r'\\server\share');
- expect(context.normalize('a\\.\\\xc5\u0bf8-;\u{1f085}\u{00}\\c\\d\\..\\'),
- 'a\\\xc5\u0bf8-;\u{1f085}\u{00}\x5cc');
+ expect(
+ context.normalize('a\\.\\\xc5\u0bf8-;\u{1f085}\u{00}\\c\\d\\..\\'),
+ 'a\\\xc5\u0bf8-;\u{1f085}\u{00}\x5cc',
+ );
});
test('collapses redundant separators', () {
@@ -403,7 +500,9 @@
expect(context.normalize(r'../..\..\'), r'..\..\..');
expect(context.normalize(r'\\server\share\..'), r'\\server\share');
expect(
- context.normalize(r'\\server\share\..\../..\a'), r'\\server\share\a');
+ context.normalize(r'\\server\share\..\../..\a'),
+ r'\\server\share\a',
+ );
expect(context.normalize(r'c:\..'), r'c:\');
expect(context.normalize(r'c:\foo\..'), r'c:\');
expect(context.normalize(r'A:/..\..\..'), r'A:\');
@@ -555,23 +654,33 @@
});
test('with a root parameter', () {
- expect(context.relative(r'C:\foo\bar\baz', from: r'C:\foo\bar'),
- equals('baz'));
expect(
- context.relative('..', from: r'C:\foo\bar'), equals(r'..\..\root'));
+ context.relative(r'C:\foo\bar\baz', from: r'C:\foo\bar'),
+ equals('baz'),
+ );
+ expect(
+ context.relative('..', from: r'C:\foo\bar'),
+ equals(r'..\..\root'),
+ );
expect(context.relative('..', from: r'D:\foo\bar'), equals(r'C:\root'));
- expect(context.relative(r'C:\foo\bar\baz', from: r'foo\bar'),
- equals(r'..\..\..\..\foo\bar\baz'));
+ expect(
+ context.relative(r'C:\foo\bar\baz', from: r'foo\bar'),
+ equals(r'..\..\..\..\foo\bar\baz'),
+ );
expect(context.relative('..', from: r'foo\bar'), equals(r'..\..\..'));
});
test('with a root parameter and a relative root', () {
- final r =
- path.Context(style: path.Style.windows, current: r'relative\root');
+ final r = path.Context(
+ style: path.Style.windows,
+ current: r'relative\root',
+ );
expect(r.relative(r'C:\foo\bar\baz', from: r'C:\foo\bar'), equals('baz'));
expect(() => r.relative('..', from: r'C:\foo\bar'), throwsPathException);
- expect(r.relative(r'C:\foo\bar\baz', from: r'foo\bar'),
- equals(r'C:\foo\bar\baz'));
+ expect(
+ r.relative(r'C:\foo\bar\baz', from: r'foo\bar'),
+ equals(r'C:\foo\bar\baz'),
+ );
expect(r.relative('..', from: r'foo\bar'), equals(r'..\..\..'));
});
@@ -697,37 +806,107 @@
expect(context.absolute('a', 'b', 'c'), r'C:\root\path\a\b\c');
expect(context.absolute('a', 'b', 'c', 'd'), r'C:\root\path\a\b\c\d');
expect(
- context.absolute('a', 'b', 'c', 'd', 'e'), r'C:\root\path\a\b\c\d\e');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
- r'C:\root\path\a\b\c\d\e\f');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
- r'C:\root\path\a\b\c\d\e\f\g');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
- r'C:\root\path\a\b\c\d\e\f\g\h');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i');
- expect(context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j');
+ context.absolute('a', 'b', 'c', 'd', 'e'),
+ r'C:\root\path\a\b\c\d\e',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f'),
+ r'C:\root\path\a\b\c\d\e\f',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g'),
+ r'C:\root\path\a\b\c\d\e\f\g',
+ );
expect(
- context.absolute(
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'),
+ r'C:\root\path\a\b\c\d\e\f\g\h',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m\n');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i',
+ );
expect(
- context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n', 'o'),
- r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o');
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j',
+ );
+ expect(
+ context.absolute('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ ),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ ),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ ),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m\n',
+ );
+ expect(
+ context.absolute(
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ ),
+ r'C:\root\path\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o',
+ );
});
test('does not add separator if a part ends in one', () {
@@ -783,34 +962,55 @@
group('fromUri', () {
test('with a URI', () {
- expect(context.fromUri(Uri.parse('file:///C:/path/to/foo')),
- r'C:\path\to\foo');
- expect(context.fromUri(Uri.parse('file:///C%3A/path/to/foo')),
- r'C:\path\to\foo');
- expect(context.fromUri(Uri.parse('file://server/share/path/to/foo')),
- r'\\server\share\path\to\foo');
+ expect(
+ context.fromUri(Uri.parse('file:///C:/path/to/foo')),
+ r'C:\path\to\foo',
+ );
+ expect(
+ context.fromUri(Uri.parse('file:///C%3A/path/to/foo')),
+ r'C:\path\to\foo',
+ );
+ expect(
+ context.fromUri(Uri.parse('file://server/share/path/to/foo')),
+ r'\\server\share\path\to\foo',
+ );
expect(context.fromUri(Uri.parse('file:///C:/')), r'C:\');
expect(context.fromUri(Uri.parse('file:///C%3A/')), r'C:\');
expect(
- context.fromUri(Uri.parse('file://server/share')), r'\\server\share');
+ context.fromUri(Uri.parse('file://server/share')),
+ r'\\server\share',
+ );
expect(context.fromUri(Uri.parse('foo/bar')), r'foo\bar');
expect(context.fromUri(Uri.parse('/C:/path/to/foo')), r'C:\path\to\foo');
expect(
- context.fromUri(Uri.parse('///C:/path/to/foo')), r'C:\path\to\foo');
- expect(context.fromUri(Uri.parse('//server/share/path/to/foo')),
- r'\\server\share\path\to\foo');
- expect(context.fromUri(Uri.parse('file:///C:/path/to/foo%23bar')),
- r'C:\path\to\foo#bar');
- expect(context.fromUri(Uri.parse('file:///C%3A/path/to/foo%23bar')),
- r'C:\path\to\foo#bar');
+ context.fromUri(Uri.parse('///C:/path/to/foo')),
+ r'C:\path\to\foo',
+ );
expect(
- context.fromUri(Uri.parse('file://server/share/path/to/foo%23bar')),
- r'\\server\share\path\to\foo#bar');
- expect(context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
- r'_{_}_`_^_ _"_%_');
+ context.fromUri(Uri.parse('//server/share/path/to/foo')),
+ r'\\server\share\path\to\foo',
+ );
+ expect(
+ context.fromUri(Uri.parse('file:///C:/path/to/foo%23bar')),
+ r'C:\path\to\foo#bar',
+ );
+ expect(
+ context.fromUri(Uri.parse('file:///C%3A/path/to/foo%23bar')),
+ r'C:\path\to\foo#bar',
+ );
+ expect(
+ context.fromUri(Uri.parse('file://server/share/path/to/foo%23bar')),
+ r'\\server\share\path\to\foo#bar',
+ );
+ expect(
+ context.fromUri(Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_')),
+ r'_{_}_`_^_ _"_%_',
+ );
expect(context.fromUri(Uri.parse('/foo')), r'\foo');
- expect(() => context.fromUri(Uri.parse('https://dart.dev')),
- throwsArgumentError);
+ expect(
+ () => context.fromUri(Uri.parse('https://dart.dev')),
+ throwsArgumentError,
+ );
});
test('with a string', () {
@@ -821,23 +1021,37 @@
test('toUri', () {
expect(
- context.toUri(r'C:\path\to\foo'), Uri.parse('file:///C:/path/to/foo'));
- expect(context.toUri(r'C:\path\to\foo\'),
- Uri.parse('file:///C:/path/to/foo/'));
+ context.toUri(r'C:\path\to\foo'),
+ Uri.parse('file:///C:/path/to/foo'),
+ );
+ expect(
+ context.toUri(r'C:\path\to\foo\'),
+ Uri.parse('file:///C:/path/to/foo/'),
+ );
expect(context.toUri(r'path\to\foo\'), Uri.parse('path/to/foo/'));
expect(context.toUri(r'C:\'), Uri.parse('file:///C:/'));
expect(context.toUri(r'\\server\share'), Uri.parse('file://server/share'));
expect(
- context.toUri(r'\\server\share\'), Uri.parse('file://server/share/'));
+ context.toUri(r'\\server\share\'),
+ Uri.parse('file://server/share/'),
+ );
expect(context.toUri(r'foo\bar'), Uri.parse('foo/bar'));
- expect(context.toUri(r'C:\path\to\foo#bar'),
- Uri.parse('file:///C:/path/to/foo%23bar'));
- expect(context.toUri(r'\\server\share\path\to\foo#bar'),
- Uri.parse('file://server/share/path/to/foo%23bar'));
- expect(context.toUri(r'C:\_{_}_`_^_ _"_%_'),
- Uri.parse('file:///C:/_%7B_%7D_%60_%5E_%20_%22_%25_'));
- expect(context.toUri(r'_{_}_`_^_ _"_%_'),
- Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'));
+ expect(
+ context.toUri(r'C:\path\to\foo#bar'),
+ Uri.parse('file:///C:/path/to/foo%23bar'),
+ );
+ expect(
+ context.toUri(r'\\server\share\path\to\foo#bar'),
+ Uri.parse('file://server/share/path/to/foo%23bar'),
+ );
+ expect(
+ context.toUri(r'C:\_{_}_`_^_ _"_%_'),
+ Uri.parse('file:///C:/_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
+ expect(
+ context.toUri(r'_{_}_`_^_ _"_%_'),
+ Uri.parse('_%7B_%7D_%60_%5E_%20_%22_%25_'),
+ );
expect(context.toUri(''), Uri.parse(''));
});
@@ -846,19 +1060,27 @@
expect(context.prettyUri('file:///C:/root/path/a/b'), r'a\b');
expect(context.prettyUri('file:///C:/root/path/a/../b'), r'b');
expect(
- context.prettyUri('file:///C:/other/path/a/b'), r'C:\other\path\a\b');
+ context.prettyUri('file:///C:/other/path/a/b'),
+ r'C:\other\path\a\b',
+ );
expect(
- context.prettyUri('file:///D:/root/path/a/b'), r'D:\root\path\a\b');
+ context.prettyUri('file:///D:/root/path/a/b'),
+ r'D:\root\path\a\b',
+ );
expect(context.prettyUri('file:///C:/root/other'), r'..\other');
});
test('with a file: URI with encoded colons', () {
expect(context.prettyUri('file:///C%3A/root/path/a/b'), r'a\b');
expect(context.prettyUri('file:///C%3A/root/path/a/../b'), r'b');
- expect(context.prettyUri('file:///C%3A/other/path/a/b'),
- r'C:\other\path\a\b');
expect(
- context.prettyUri('file:///D%3A/root/path/a/b'), r'D:\root\path\a\b');
+ context.prettyUri('file:///C%3A/other/path/a/b'),
+ r'C:\other\path\a\b',
+ );
+ expect(
+ context.prettyUri('file:///D%3A/root/path/a/b'),
+ r'D:\root\path\a\b',
+ );
expect(context.prettyUri('file:///C%3A/root/other'), r'..\other');
});
diff --git a/pkgs/platform/CHANGELOG.md b/pkgs/platform/CHANGELOG.md
index 1e8c4d5..161b705 100644
--- a/pkgs/platform/CHANGELOG.md
+++ b/pkgs/platform/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 3.1.7-wip
+
+- Run `dart format` with the new style.
+
## 3.1.6
* Move to `dart-lang/core` monorepo.
diff --git a/pkgs/platform/lib/src/testing/fake_platform.dart b/pkgs/platform/lib/src/testing/fake_platform.dart
index 0c028ca..ca611d8 100644
--- a/pkgs/platform/lib/src/testing/fake_platform.dart
+++ b/pkgs/platform/lib/src/testing/fake_platform.dart
@@ -192,7 +192,8 @@
T _throwIfNull<T>(T? value) {
if (value == null) {
throw StateError(
- 'Tried to read property of FakePlatform but it was unset.');
+ 'Tried to read property of FakePlatform but it was unset.',
+ );
}
return value;
}
diff --git a/pkgs/platform/pubspec.yaml b/pkgs/platform/pubspec.yaml
index 2507672..3f72086 100644
--- a/pkgs/platform/pubspec.yaml
+++ b/pkgs/platform/pubspec.yaml
@@ -2,7 +2,7 @@
description: A pluggable, mockable platform information abstraction for Dart.
repository: https://github.com/dart-lang/core/tree/main/pkgs/platform
issue_tracker: https://github.com/dart-lang/core/issues
-version: 3.1.6
+version: 3.1.7-wip
topics:
- information
diff --git a/pkgs/platform/test/fake_platform_test.dart b/pkgs/platform/test/fake_platform_test.dart
index 1aa7cbf..424133d 100644
--- a/pkgs/platform/test/fake_platform_test.dart
+++ b/pkgs/platform/test/fake_platform_test.dart
@@ -50,7 +50,9 @@
expect(fake.environment[key], 'FAKE');
expect(
- fake.executableArguments.length, local.executableArguments.length);
+ fake.executableArguments.length,
+ local.executableArguments.length,
+ );
fake.executableArguments.add('ARG');
expect(fake.executableArguments.last, 'ARG');
});
@@ -62,9 +64,7 @@
});
test('overrides a value, but leaves others intact', () {
- final copy = fake.copyWith(
- numberOfProcessors: -1,
- );
+ final copy = fake.copyWith(numberOfProcessors: -1);
expect(copy.numberOfProcessors, equals(-1));
expect(copy.pathSeparator, local.pathSeparator);
expect(copy.operatingSystem, local.operatingSystem);
diff --git a/pkgs/typed_data/CHANGELOG.md b/pkgs/typed_data/CHANGELOG.md
index 8763a87..30858e7 100644
--- a/pkgs/typed_data/CHANGELOG.md
+++ b/pkgs/typed_data/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 1.4.1-wip
+
+- Run `dart format` with the new style.
+
## 1.4.0
* The type of the `buffer` constructor argument to `TypedDataBuffer` is now
diff --git a/pkgs/typed_data/lib/src/typed_buffer.dart b/pkgs/typed_data/lib/src/typed_buffer.dart
index dcb2c58..50ccd24 100644
--- a/pkgs/typed_data/lib/src/typed_buffer.dart
+++ b/pkgs/typed_data/lib/src/typed_buffer.dart
@@ -203,7 +203,11 @@
_ensureCapacity(newLength);
_buffer.setRange(
- index + valuesLength, _length + valuesLength, _buffer, index);
+ index + valuesLength,
+ _length + valuesLength,
+ _buffer,
+ index,
+ );
_buffer.setRange(index, index + valuesLength, values, start);
_length = newLength;
}
diff --git a/pkgs/typed_data/lib/src/typed_queue.dart b/pkgs/typed_data/lib/src/typed_queue.dart
index 84ce529..2147411 100644
--- a/pkgs/typed_data/lib/src/typed_queue.dart
+++ b/pkgs/typed_data/lib/src/typed_queue.dart
@@ -188,8 +188,12 @@
// [ |===========| sourceEnd ]
// sourceStart
_table.setRange(targetStart, _table.length, _table, sourceStart);
- _table.setRange(0, targetEnd, _table,
- sourceStart + (_table.length - targetStart));
+ _table.setRange(
+ 0,
+ targetEnd,
+ _table,
+ sourceStart + (_table.length - targetStart),
+ );
} else {
// targetEnd
// [ targetStart |===========| ]
@@ -206,8 +210,12 @@
// [=====| targetEnd targetStart |======]
// [ sourceStart |===========| ]
// sourceEnd
- _table.setRange(0, targetEnd, _table,
- sourceStart + (_table.length - targetStart));
+ _table.setRange(
+ 0,
+ targetEnd,
+ _table,
+ sourceStart + (_table.length - targetStart),
+ );
_table.setRange(targetStart, _table.length, _table, sourceStart);
} else {
// targetStart
@@ -227,7 +235,11 @@
// not this queue), set it with two underlying [setRange] calls.
_table.setRange(targetStart, _table.length, iterable, skipCount);
_table.setRange(
- 0, targetEnd, iterable, skipCount + (_table.length - targetStart));
+ 0,
+ targetEnd,
+ iterable,
+ skipCount + (_table.length - targetStart),
+ );
} else {
// If [iterable] isn't a [List], we don't want to make two different
// [setRange] calls because it could materialize a lazy iterable twice.
diff --git a/pkgs/typed_data/pubspec.yaml b/pkgs/typed_data/pubspec.yaml
index 6c93be6..678818d 100644
--- a/pkgs/typed_data/pubspec.yaml
+++ b/pkgs/typed_data/pubspec.yaml
@@ -1,5 +1,5 @@
name: typed_data
-version: 1.4.0
+version: 1.4.1-wip
description: >-
Utility functions and classes related to the dart:typed_data library.
repository: https://github.com/dart-lang/core/tree/main/pkgs/typed_data
diff --git a/pkgs/typed_data/test/queue_test.dart b/pkgs/typed_data/test/queue_test.dart
index c0b1368..d9803c6 100644
--- a/pkgs/typed_data/test/queue_test.dart
+++ b/pkgs/typed_data/test/queue_test.dart
@@ -95,16 +95,46 @@
group('sets a range to the contents of an iterable', () {
forEachInternalRepresentation((queue) {
queue.setRange(5, 10, oneThrough(10).map((n) => 100 + n), 2);
- expect(queue,
- [1, 2, 3, 4, 5, 103, 104, 105, 106, 107, 11, 12, 13, 14, 15]);
+ expect(queue, [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 103,
+ 104,
+ 105,
+ 106,
+ 107,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ ]);
});
});
group('sets a range to the contents of a list', () {
forEachInternalRepresentation((queue) {
queue.setRange(5, 10, oneThrough(10).map((n) => 100 + n).toList(), 2);
- expect(queue,
- [1, 2, 3, 4, 5, 103, 104, 105, 106, 107, 11, 12, 13, 14, 15]);
+ expect(queue, [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 103,
+ 104,
+ 105,
+ 106,
+ 107,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ ]);
});
});
@@ -117,13 +147,15 @@
});
});
- group('sets a range to a section of the same queue overlapping at the end',
- () {
- forEachInternalRepresentation((queue) {
- queue.setRange(5, 10, queue, 6);
- expect(queue, [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15]);
- });
- });
+ group(
+ 'sets a range to a section of the same queue overlapping at the end',
+ () {
+ forEachInternalRepresentation((queue) {
+ queue.setRange(5, 10, queue, 6);
+ expect(queue, [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15]);
+ });
+ },
+ );
test('throws a RangeError for an invalid range', () {
expect(() => Uint8Queue().setRange(0, 1, [1]), throwsRangeError);
@@ -155,9 +187,11 @@
forEachInternalRepresentation((queue) {
queue.length = 20;
expect(
- queue,
- equals(oneThrough(capacity - 1) +
- List.filled(20 - (capacity - 1), 0)));
+ queue,
+ equals(
+ oneThrough(capacity - 1) + List.filled(20 - (capacity - 1), 0),
+ ),
+ );
});
});
@@ -230,33 +264,45 @@
});
test('add', () {
- expect(() => queue.forEach((_) => queue.add(4)),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.add(4)),
+ throwsConcurrentModificationError,
+ );
});
test('addAll', () {
- expect(() => queue.forEach((_) => queue.addAll([4, 5, 6])),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.addAll([4, 5, 6])),
+ throwsConcurrentModificationError,
+ );
});
test('addFirst', () {
- expect(() => queue.forEach((_) => queue.addFirst(0)),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.addFirst(0)),
+ throwsConcurrentModificationError,
+ );
});
test('removeFirst', () {
- expect(() => queue.forEach((_) => queue.removeFirst()),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.removeFirst()),
+ throwsConcurrentModificationError,
+ );
});
test('removeLast', () {
- expect(() => queue.forEach((_) => queue.removeLast()),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.removeLast()),
+ throwsConcurrentModificationError,
+ );
});
test('length=', () {
- expect(() => queue.forEach((_) => queue.length = 1),
- throwsConcurrentModificationError);
+ expect(
+ () => queue.forEach((_) => queue.length = 1),
+ throwsConcurrentModificationError,
+ );
});
});
}
@@ -311,5 +357,6 @@
/// Returns a matcher that expects that a closure throws a
/// [ConcurrentModificationError].
-final throwsConcurrentModificationError =
- throwsA(const TypeMatcher<ConcurrentModificationError>());
+final throwsConcurrentModificationError = throwsA(
+ const TypeMatcher<ConcurrentModificationError>(),
+);
diff --git a/pkgs/typed_data/test/typed_buffers_test.dart b/pkgs/typed_data/test/typed_buffers_test.dart
index 9d73040..937407b 100644
--- a/pkgs/typed_data/test/typed_buffers_test.dart
+++ b/pkgs/typed_data/test/typed_buffers_test.dart
@@ -38,7 +38,7 @@
0x55,
0x02,
0x01,
- 0x00
+ 0x00,
];
void main() {
@@ -57,12 +57,20 @@
testInt(intSamples, 32, Int32Buffer.new);
- testUint(intSamples, 64, Uint64Buffer.new,
- // JS doesn't support 64-bit ints, so only test this on the VM.
- testOn: 'dart-vm');
- testInt(intSamples, 64, Int64Buffer.new,
- // JS doesn't support 64-bit ints, so only test this on the VM.
- testOn: 'dart-vm');
+ testUint(
+ intSamples,
+ 64,
+ Uint64Buffer.new,
+ // JS doesn't support 64-bit ints, so only test this on the VM.
+ testOn: 'dart-vm',
+ );
+ testInt(
+ intSamples,
+ 64,
+ Int64Buffer.new,
+ // JS doesn't support 64-bit ints, so only test this on the VM.
+ testOn: 'dart-vm',
+ );
testInt32x4Buffer(intSamples);
@@ -203,7 +211,7 @@
0.0 / 0.0, // NaN.
0.49999999999999994, // Round-traps 1-3 (adding 0.5 and rounding towards
4503599627370497.0, // minus infinity will not be the same as rounding
- 9007199254740991.0 // to nearest with 0.5 rounding up).
+ 9007199254740991.0, // to nearest with 0.5 rounding up).
];
const floatSamples = [
@@ -221,7 +229,7 @@
0.0 / 0.0, // NaN.
0.99999994, // Round traps 1-3.
8388609.0,
- 16777215.0
+ 16777215.0,
];
int clampUint8(int x) => x < 0
@@ -251,8 +259,14 @@
void testFloat32x4Buffer(List<double> floatSamples) {
var float4Samples = <Float32x4>[];
for (var i = 0; i < floatSamples.length - 3; i++) {
- float4Samples.add(Float32x4(floatSamples[i], floatSamples[i + 1],
- floatSamples[i + 2], floatSamples[i + 3]));
+ float4Samples.add(
+ Float32x4(
+ floatSamples[i],
+ floatSamples[i + 1],
+ floatSamples[i + 2],
+ floatSamples[i + 3],
+ ),
+ );
}
void floatEquals(num x, num y) {
diff --git a/pkgs/typed_data/test/typed_buffers_vm_test.dart b/pkgs/typed_data/test/typed_buffers_vm_test.dart
index 62afcef..8569191 100644
--- a/pkgs/typed_data/test/typed_buffers_vm_test.dart
+++ b/pkgs/typed_data/test/typed_buffers_vm_test.dart
@@ -17,8 +17,5 @@
0x7fffffffffffffff,
0x5555555555555555,
];
- initTests(<int>[
- ...browserSafeIntSamples,
- ...browserUnsafe,
- ]);
+ initTests(<int>[...browserSafeIntSamples, ...browserUnsafe]);
}