From a130bf56d72c1313b98bbd7e1cbb7f4d9e559d32 Mon Sep 17 00:00:00 2001 From: Moritz Date: Thu, 24 Apr 2025 08:07:23 +0200 Subject: [PATCH 1/4] Format `package:async` --- pkgs/async/CHANGELOG.md | 1 + pkgs/async/lib/src/async_cache.dart | 13 +- pkgs/async/lib/src/byte_collector.dart | 28 +- pkgs/async/lib/src/cancelable_operation.dart | 198 ++++--- pkgs/async/lib/src/chunked_stream_reader.dart | 5 +- pkgs/async/lib/src/delegate/event_sink.dart | 3 +- pkgs/async/lib/src/delegate/sink.dart | 3 +- .../lib/src/delegate/stream_consumer.dart | 3 +- pkgs/async/lib/src/delegate/stream_sink.dart | 3 +- pkgs/async/lib/src/lazy_stream.dart | 16 +- pkgs/async/lib/src/result/result.dart | 6 +- .../src/single_subscription_transformer.dart | 30 +- pkgs/async/lib/src/sink_base.dart | 12 +- pkgs/async/lib/src/stream_closer.dart | 8 +- pkgs/async/lib/src/stream_completer.dart | 24 +- pkgs/async/lib/src/stream_extensions.dart | 42 +- pkgs/async/lib/src/stream_group.dart | 23 +- pkgs/async/lib/src/stream_queue.dart | 46 +- .../lib/src/stream_sink_transformer.dart | 15 +- .../handler_transformer.dart | 19 +- .../reject_errors.dart | 7 +- .../stream_transformer_wrapper.dart | 22 +- pkgs/async/lib/src/stream_splitter.dart | 12 +- .../src/stream_subscription_transformer.dart | 36 +- pkgs/async/lib/src/stream_zip.dart | 66 ++- pkgs/async/lib/src/subscription_stream.dart | 8 +- .../lib/src/typed_stream_transformer.dart | 3 +- pkgs/async/test/async_cache_test.dart | 77 ++- pkgs/async/test/byte_collection_test.dart | 42 +- .../async/test/cancelable_operation_test.dart | 495 +++++++++++------- pkgs/async/test/chunked_stream_reader.dart | 7 +- pkgs/async/test/future_group_test.dart | 59 ++- pkgs/async/test/lazy_stream_test.dart | 30 +- pkgs/async/test/null_stream_sink_test.dart | 36 +- pkgs/async/test/reject_errors_test.dart | 27 +- pkgs/async/test/restartable_timer_test.dart | 4 +- .../test/result/result_captureAll_test.dart | 23 +- .../test/result/result_flattenAll_test.dart | 20 +- .../async/test/result/result_future_test.dart | 6 +- pkgs/async/test/result/result_test.dart | 223 +++++--- .../single_subscription_transformer_test.dart | 48 +- pkgs/async/test/sink_base_test.dart | 170 +++--- pkgs/async/test/stream_closer_test.dart | 82 +-- pkgs/async/test/stream_completer_test.dart | 131 +++-- pkgs/async/test/stream_extensions_test.dart | 116 ++-- pkgs/async/test/stream_group_test.dart | 446 +++++++++------- pkgs/async/test/stream_queue_test.dart | 298 ++++++----- .../test/stream_sink_completer_test.dart | 52 +- .../test/stream_sink_transformer_test.dart | 142 +++-- pkgs/async/test/stream_splitter_test.dart | 111 ++-- pkgs/async/test/stream_zip_test.dart | 329 +++++++----- pkgs/async/test/stream_zip_zone_test.dart | 66 ++- pkgs/async/test/subscription_stream_test.dart | 102 ++-- .../test/subscription_transformer_test.dart | 169 +++--- .../stream_subscription_test.dart | 45 +- pkgs/async/test/utils.dart | 27 +- 56 files changed, 2418 insertions(+), 1617 deletions(-) diff --git a/pkgs/async/CHANGELOG.md b/pkgs/async/CHANGELOG.md index 1f6d74dac..5e5d952ac 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 6fc7cb0e5..f86b0600a 100644 --- a/pkgs/async/lib/src/async_cache.dart +++ b/pkgs/async/lib/src/async_cache.dart @@ -85,10 +85,15 @@ class AsyncCache { 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 0c937616b..a91a7326c 100644 --- a/pkgs/async/lib/src/byte_collector.dart +++ b/pkgs/async/lib/src/byte_collector.dart @@ -28,11 +28,13 @@ Future collectBytes(Stream> source) { /// 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 collectBytesCancelable( - Stream> source) { + Stream> 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 @@ CancelableOperation collectBytesCancelable( /// 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(Stream> source, - T Function(StreamSubscription>, Future) result) { +T _collectBytes( + Stream> source, + T Function(StreamSubscription>, Future) result, +) { var bytes = BytesBuilder(copy: false); var completer = Completer.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 2610613c3..112acbe3b 100644 --- a/pkgs/async/lib/src/cancelable_operation.dart +++ b/pkgs/async/lib/src/cancelable_operation.dart @@ -29,8 +29,10 @@ class CancelableOperation { /// /// Calling this constructor is equivalent to creating a /// [CancelableCompleter] and completing it with [result]. - factory CancelableOperation.fromFuture(Future result, - {FutureOr Function()? onCancel}) => + factory CancelableOperation.fromFuture( + Future result, { + FutureOr Function()? onCancel, + }) => (CancelableCompleter(onCancel: onCancel)..complete(result)).operation; /// Creates a [CancelableOperation] which completes to [value]. @@ -51,7 +53,8 @@ class CancelableOperation { /// subscription will be canceled (unlike /// `CancelableOperation.fromFuture(subscription.asFuture())`). static CancelableOperation fromSubscription( - StreamSubscription subscription) { + StreamSubscription subscription, + ) { var completer = CancelableCompleter(onCancel: subscription.cancel); subscription.onDone(completer.complete); subscription.onError((Object error, StackTrace stackTrace) { @@ -70,7 +73,8 @@ class CancelableOperation { /// new operation is cancelled, all the [operations] are cancelled as /// well. static CancelableOperation race( - Iterable> operations) { + Iterable> operations, + ) { operations = operations.toList(); if (operations.isEmpty) { throw ArgumentError('May not be empty', 'operations'); @@ -83,20 +87,25 @@ class CancelableOperation { done = true; return Future.wait([ for (var operation in operations) - if (!operation.isCanceled) operation.cancel() + if (!operation.isCanceled) operation.cancel(), ]); } var completer = CancelableCompleter(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 @@ class CancelableOperation { /// This is like `value.asStream()`, but if a subscription to the stream is /// canceled, this operation is as well. Stream asStream() { - var controller = - StreamController(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(); - }); + var controller = StreamController( + 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(); + }, + ); return controller.stream; } @@ -172,24 +186,28 @@ class CancelableOperation { /// 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 then(FutureOr Function(T) onValue, - {FutureOr Function(Object, StackTrace)? onError, - FutureOr Function()? onCancel, - bool propagateCancel = true}) => - thenOperation((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 then( + FutureOr Function(T) onValue, { + FutureOr Function(Object, StackTrace)? onError, + FutureOr Function()? onCancel, + bool propagateCancel = true, + }) => + thenOperation( + (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 @@ class CancelableOperation { /// listeners on this operation and canceling the [onValue], [onError], and /// [onCancel] callbacks should not cancel the other listeners. CancelableOperation thenOperation( - FutureOr Function(T, CancelableCompleter) onValue, - {FutureOr Function(Object, StackTrace, CancelableCompleter)? - onError, - FutureOr Function(CancelableCompleter)? onCancel, - bool propagateCancel = true}) { + FutureOr Function(T, CancelableCompleter) onValue, { + FutureOr Function(Object, StackTrace, CancelableCompleter)? + onError, + FutureOr Function(CancelableCompleter)? onCancel, + bool propagateCancel = true, + }) { final completer = CancelableCompleter( - 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 @@ class CancelableOperation { // completes before `completer` is cancelled, // then cancel `cancelCompleter`. (Cancelling twice is safe.) - _completer._inner?.future.then((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( + (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(completer, onCancel); if (_completer.isCanceled) { cancelForwarder._forward(); @@ -430,11 +454,14 @@ class CancelableCompleter { 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 @@ class CancelableCompleter { /// 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 result, - {bool propagateCancel = true}) { + void completeOperation( + CancelableOperation result, { + bool propagateCancel = true, + }) { if (!_mayComplete) throw StateError('Already completed'); _mayComplete = false; if (isCanceled) { @@ -452,14 +481,19 @@ class CancelableCompleter { result.value.ignore(); return; } - result.then((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( + (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 @@ class CancelableCompleter { final isFuture = toReturn is Future; final cancelFutures = >[ 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 1d92216a3..23c8423d3 100644 --- a/pkgs/async/lib/src/chunked_stream_reader.dart +++ b/pkgs/async/lib/src/chunked_stream_reader.dart @@ -140,7 +140,10 @@ class ChunkedStreamReader { List output; if (_buffer is Uint8List) { output = Uint8List.sublistView( - _buffer as Uint8List, _offset, _offset + size) as List; + _buffer as Uint8List, + _offset, + _offset + size, + ) as List; } 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 34c119b58..23c4065c7 100644 --- a/pkgs/async/lib/src/delegate/event_sink.dart +++ b/pkgs/async/lib/src/delegate/event_sink.dart @@ -23,7 +23,8 @@ class DelegatingEventSink implements EventSink { /// [add] may throw a [TypeError] if the argument type doesn't match the /// reified type of [sink]. @Deprecated( - 'Use StreamController(sync: true)..stream.cast().pipe(sink)') + 'Use StreamController(sync: true)..stream.cast().pipe(sink)', + ) static EventSink typed(EventSink sink) => sink is EventSink ? sink : DelegatingEventSink._(sink); diff --git a/pkgs/async/lib/src/delegate/sink.dart b/pkgs/async/lib/src/delegate/sink.dart index a1954f0de..a84d6f1d7 100644 --- a/pkgs/async/lib/src/delegate/sink.dart +++ b/pkgs/async/lib/src/delegate/sink.dart @@ -21,7 +21,8 @@ class DelegatingSink implements Sink { /// throw a [TypeError] if the argument type doesn't match the reified type of /// [sink]. @Deprecated( - 'Use StreamController(sync: true)..stream.cast().pipe(sink)') + 'Use StreamController(sync: true)..stream.cast().pipe(sink)', + ) static Sink typed(Sink sink) => sink is Sink ? sink : DelegatingSink._(sink); diff --git a/pkgs/async/lib/src/delegate/stream_consumer.dart b/pkgs/async/lib/src/delegate/stream_consumer.dart index c911c4142..9e1fd95be 100644 --- a/pkgs/async/lib/src/delegate/stream_consumer.dart +++ b/pkgs/async/lib/src/delegate/stream_consumer.dart @@ -23,7 +23,8 @@ class DelegatingStreamConsumer implements StreamConsumer { /// calls to [addStream] may throw a [TypeError] if the argument type doesn't /// match the reified type of [consumer]. @Deprecated( - 'Use StreamController(sync: true)..stream.cast().pipe(sink)') + 'Use StreamController(sync: true)..stream.cast().pipe(sink)', + ) static StreamConsumer typed(StreamConsumer consumer) => consumer is StreamConsumer ? consumer diff --git a/pkgs/async/lib/src/delegate/stream_sink.dart b/pkgs/async/lib/src/delegate/stream_sink.dart index e6edd2ff2..cd1cd0ead 100644 --- a/pkgs/async/lib/src/delegate/stream_sink.dart +++ b/pkgs/async/lib/src/delegate/stream_sink.dart @@ -26,7 +26,8 @@ class DelegatingStreamSink implements StreamSink { /// throw a [TypeError] if the argument type doesn't match the reified type of /// [sink]. @Deprecated( - 'Use StreamController(sync: true)..stream.cast().pipe(sink)') + 'Use StreamController(sync: true)..stream.cast().pipe(sink)', + ) static StreamSink typed(StreamSink sink) => sink is StreamSink ? sink : DelegatingStreamSink._(sink); diff --git a/pkgs/async/lib/src/lazy_stream.dart b/pkgs/async/lib/src/lazy_stream.dart index e0facaa51..48fe970fd 100644 --- a/pkgs/async/lib/src/lazy_stream.dart +++ b/pkgs/async/lib/src/lazy_stream.dart @@ -24,8 +24,12 @@ class LazyStream extends Stream { } @override - StreamSubscription listen(void Function(T)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription 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 @@ class LazyStream extends Stream { 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 124ccefaf..616467373 100644 --- a/pkgs/async/lib/src/result/result.dart +++ b/pkgs/async/lib/src/result/result.dart @@ -44,7 +44,8 @@ abstract class Result { static const StreamSinkTransformer> captureSinkTransformer = StreamSinkTransformer>.fromStreamTransformer( - CaptureStreamTransformer()); + CaptureStreamTransformer(), + ); /// A sink transformer that releases result events. /// @@ -53,7 +54,8 @@ abstract class Result { static const StreamSinkTransformer, Object> releaseSinkTransformer = StreamSinkTransformer, Object>.fromStreamTransformer( - ReleaseStreamTransformer()); + ReleaseStreamTransformer(), + ); /// 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 ba6f0d2e0..b41653b44 100644 --- a/pkgs/async/lib/src/single_subscription_transformer.dart +++ b/pkgs/async/lib/src/single_subscription_transformer.dart @@ -19,18 +19,24 @@ class SingleSubscriptionTransformer extends StreamTransformerBase { @override Stream bind(Stream stream) { late StreamSubscription subscription; - var controller = - StreamController(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( + 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 f1d7d14b5..f50256b0f 100644 --- a/pkgs/async/lib/src/sink_base.dart +++ b/pkgs/async/lib/src/sink_base.dart @@ -77,10 +77,14 @@ abstract class StreamSinkBase extends EventSinkBase _addingStream = true; var completer = Completer.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 91546242c..552ac16d0 100644 --- a/pkgs/async/lib/src/stream_closer.dart +++ b/pkgs/async/lib/src/stream_closer.dart @@ -38,7 +38,7 @@ class StreamCloser extends StreamTransformerBase { /// ignored. Future close() => _closeFuture ??= () { var futures = [ - for (var subscription in _subscriptions) subscription.cancel() + for (var subscription in _subscriptions) subscription.cancel(), ]; _subscriptions.clear(); @@ -71,8 +71,10 @@ class StreamCloser extends StreamTransformerBase { 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 27034c2fe..b916f037c 100644 --- a/pkgs/async/lib/src/stream_completer.dart +++ b/pkgs/async/lib/src/stream_completer.dart @@ -117,23 +117,35 @@ class _CompleterStream extends Stream { Stream? _sourceStream; @override - StreamSubscription listen(void Function(T)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription 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 4ba9254fa..750ee2798 100644 --- a/pkgs/async/lib/src/stream_extensions.dart +++ b/pkgs/async/lib/src/stream_extensions.dart @@ -22,16 +22,21 @@ extension StreamExtensions on Stream { if (length < 1) throw RangeError.range(length, 1, null, 'length'); var slice = []; - 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 @@ extension StreamExtensions on Stream { /// completed with `null`. Future get firstOrNull { var completer = Completer.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 @@ extension StreamExtensions on Stream { /// clear that the data isn't not needed. Stream listenAndBuffer() { var controller = StreamController(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 e02afcd2c..51da7b99b 100644 --- a/pkgs/async/lib/src/stream_group.dart +++ b/pkgs/async/lib/src/stream_group.dart @@ -109,17 +109,21 @@ class StreamGroup implements Sink> { /// Creates a new stream group where [stream] is single-subscriber. StreamGroup() { _controller = StreamController( - 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.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 @@ class StreamGroup implements Sink> { /// /// This will pause the resulting subscription if `this` is paused. StreamSubscription _listenToStream(Stream 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 c5c0c196a..7017a067d 100644 --- a/pkgs/async/lib/src/stream_queue.dart +++ b/pkgs/async/lib/src/stream_queue.dart @@ -317,7 +317,8 @@ class StreamQueue { /// } /// ``` Future withTransaction( - Future Function(StreamQueue) callback) async { + Future Function(StreamQueue) callback, + ) async { var transaction = startTransaction(); var queue = transaction.newQueue(); @@ -356,16 +357,21 @@ class StreamQueue { /// _stdinQueue.cancelable((queue) => queue.next); /// ``` CancelableOperation cancelable( - Future Function(StreamQueue) callback) { + Future Function(StreamQueue) callback, + ) { var transaction = startTransaction(); - var completer = CancelableCompleter(onCancel: () { - transaction.reject(); - }); + var completer = CancelableCompleter( + 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 @@ class StreamQueue { 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 @@ class _SkipRequest implements _EventRequest { 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 c1ed74785..ebfd4cc0a 100644 --- a/pkgs/async/lib/src/stream_sink_transformer.dart +++ b/pkgs/async/lib/src/stream_sink_transformer.dart @@ -24,7 +24,8 @@ abstract class StreamSinkTransformer { /// 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 transformer) = StreamTransformerWrapper; + StreamTransformer transformer, + ) = StreamTransformerWrapper; /// Creates a [StreamSinkTransformer] that delegates events to the given /// handlers. @@ -33,10 +34,11 @@ abstract class StreamSinkTransformer { /// 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)? handleData, - void Function(Object, StackTrace, EventSink)? handleError, - void Function(EventSink)? handleDone}) { + factory StreamSinkTransformer.fromHandlers({ + void Function(S, EventSink)? handleData, + void Function(Object, StackTrace, EventSink)? handleError, + void Function(EventSink)? handleDone, + }) { return HandlerTransformer(handleData, handleError, handleDone); } @@ -56,7 +58,8 @@ abstract class StreamSinkTransformer { @Deprecated('Will be removed in future version') // TODO remove TypeSafeStreamSinkTransformer static StreamSinkTransformer typed( - StreamSinkTransformer transformer) => + StreamSinkTransformer transformer, + ) => transformer is StreamSinkTransformer ? 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 496c7ca4b..2deaea895 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 @@ class _HandlerSink implements StreamSink { 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 stream) { - return _inner.addStream(stream.transform( + return _inner.addStream( + stream.transform( StreamTransformer.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 6d077f469..fbed1a370 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 @@ class RejectErrorsSink implements StreamSink { 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 b30e8ad7c..4f9fb522d 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 @@ class _StreamTransformerWrapperSink implements StreamSink { Future get done => _inner.done; _StreamTransformerWrapperSink( - StreamTransformer 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 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 f7377d67c..a02f9d787 100644 --- a/pkgs/async/lib/src/stream_splitter.dart +++ b/pkgs/async/lib/src/stream_splitter.dart @@ -76,7 +76,10 @@ class StreamSplitter { } var controller = StreamController( - 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 @@ class StreamSplitter { // 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 d03ea7000..4706d440e 100644 --- a/pkgs/async/lib/src/stream_subscription_transformer.dart +++ b/pkgs/async/lib/src/stream_subscription_transformer.dart @@ -27,22 +27,24 @@ typedef _VoidHandler = void Function(StreamSubscription inner); /// synchronously call the corresponding method** on the inner /// [StreamSubscription]: [handleCancel] must call `cancel()`, [handlePause] /// must call `pause()`, and [handleResume] must call `resume()`. -StreamTransformer subscriptionTransformer( - {Future Function(StreamSubscription)? handleCancel, - void Function(StreamSubscription)? handlePause, - void Function(StreamSubscription)? handleResume}) { +StreamTransformer subscriptionTransformer({ + Future Function(StreamSubscription)? handleCancel, + void Function(StreamSubscription)? handlePause, + void Function(StreamSubscription)? 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 @@ class _TransformedSubscription implements StreamSubscription { 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 f5b8296d5..93f281d36 100644 --- a/pkgs/async/lib/src/stream_zip.dart +++ b/pkgs/async/lib/src/stream_zip.dart @@ -18,8 +18,12 @@ class StreamZip extends Stream> { StreamZip(Iterable> streams) : _streams = streams; @override - StreamSubscription> listen(void Function(List)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription> listen( + void Function(List)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { cancelOnError = identical(true, cancelOnError); var subscriptions = >[]; late StreamController> controller; @@ -71,12 +75,16 @@ class StreamZip extends Stream> { 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 @@ class StreamZip extends Stream> { current = List.filled(subscriptions.length, null); - controller = StreamController>(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>( + 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 e6630721a..6a7aeb8aa 100644 --- a/pkgs/async/lib/src/subscription_stream.dart +++ b/pkgs/async/lib/src/subscription_stream.dart @@ -40,8 +40,12 @@ class SubscriptionStream extends Stream { } @override - StreamSubscription listen(void Function(T)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription 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 8a3922879..90cd7c3e5 100644 --- a/pkgs/async/lib/src/typed_stream_transformer.dart +++ b/pkgs/async/lib/src/typed_stream_transformer.dart @@ -12,7 +12,8 @@ import 'dart:async'; /// provided. If they're not, the stream throws a [TypeError]. @Deprecated('Use Stream.cast after binding a transformer instead') StreamTransformer typedStreamTransformer( - StreamTransformer transformer) => + StreamTransformer transformer, +) => transformer is StreamTransformer ? transformer : _TypeSafeStreamTransformer(transformer); diff --git a/pkgs/async/test/async_cache_test.dart b/pkgs/async/test/async_cache_test.dart index f7c8caa6e..47204e6a5 100644 --- a/pkgs/async/test/async_cache_test.dart +++ b/pkgs/async/test/async_cache_test.dart @@ -24,8 +24,10 @@ void main() { 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 @@ void main() { var completer = Completer(); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { } 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 @@ void main() { Stream 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 67f319b09..63c113647 100644 --- a/pkgs/async/test/byte_collection_test.dart +++ b/pkgs/async/test/byte_collection_test.dart @@ -10,12 +10,14 @@ import 'package:test/test.dart'; 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 @@ void main() { }); 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 @@ void main() { }); 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 3b096e428..d7cbcd516 100644 --- a/pkgs/async/test/cancelable_operation_test.dart +++ b/pkgs/async/test/cancelable_operation_test.dart @@ -58,36 +58,43 @@ void main() { 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 @@ void main() { test('successfully then with a future', () { completer.complete(1); - expect(() => completer.complete(Completer().future), - throwsStateError); + expect( + () => completer.complete(Completer().future), + throwsStateError, + ); }); test('with a future then successfully', () { @@ -143,8 +152,10 @@ void main() { test('with a future twice', () { completer.complete(Completer().future); - expect(() => completer.complete(Completer().future), - throwsStateError); + expect( + () => completer.complete(Completer().future), + throwsStateError, + ); }); }); @@ -164,8 +175,9 @@ void main() { test('forwards a done event once it completes', () async { var controller = StreamController(); var operationCompleted = false; - CancelableOperation.fromSubscription(controller.stream.listen(null)) - .then((_) { + CancelableOperation.fromSubscription( + controller.stream.listen(null), + ).then((_) { operationCompleted = true; }); @@ -179,7 +191,8 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { }); 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(); - var completer = - CancelableCompleter(onCancel: () => innerCompleter.future); + var completer = CancelableCompleter( + onCancel: () => innerCompleter.future, + ); var fired = false; completer.operation.valueOrCancellation().then((_) { @@ -299,63 +321,72 @@ void main() { expect(fired, isTrue); }); - test('CancelableOperation.fromSubscription() cancels the subscription', - () async { - var cancelCompleter = Completer(); - var canceled = false; - var controller = StreamController(onCancel: () { - canceled = true; - return cancelCompleter.future; - }); - var operation = - CancelableOperation.fromSubscription(controller.stream.listen(null)); + test( + 'CancelableOperation.fromSubscription() cancels the subscription', + () async { + var cancelCompleter = Completer(); + var canceled = false; + var controller = StreamController( + 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(); completer.operation.value.whenComplete(expectAsync0(() {}, count: 0)); - completer - .completeOperation(CancelableCompleter().operation..cancel()); + completer.completeOperation( + CancelableCompleter().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().operation..cancel(); - await operation.valueOrCancellation(); - final completer = CancelableCompleter(); - 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().operation..cancel(); + await operation.valueOrCancellation(); + final completer = CancelableCompleter(); + 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(); - final operation = - CancelableCompleter(onCancel: expectAsync0(() {}, count: 1)) - .operation; + final operation = CancelableCompleter( + onCancel: expectAsync0(() {}, count: 1), + ).operation; completer.completeOperation(operation); completer.operation.cancel(); }); @@ -363,29 +394,31 @@ void main() { test('propagates cancellation from already canceld completer', () async { final completer = CancelableCompleter()..operation.cancel(); await completer.operation.valueOrCancellation(); - final operation = - CancelableCompleter(onCancel: expectAsync0(() {}, count: 1)) - .operation; + final operation = CancelableCompleter( + onCancel: expectAsync0(() {}, count: 1), + ).operation; completer.completeOperation(operation); }); test('cancel propagation can be disabled', () { final completer = CancelableCompleter(); - final operation = - CancelableCompleter(onCancel: expectAsync0(() {}, count: 0)) - .operation; + final operation = CancelableCompleter( + 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()..operation.cancel(); - await completer.operation.valueOrCancellation(); - final operation = - CancelableCompleter(onCancel: expectAsync0(() {}, count: 0)) - .operation; - completer.completeOperation(operation, propagateCancel: false); - }); + test( + 'cancel propagation can be disabled from already canceled completed', + () async { + final completer = CancelableCompleter()..operation.cancel(); + await completer.operation.valueOrCancellation(); + final operation = CancelableCompleter( + onCancel: expectAsync0(() {}, count: 0), + ).operation; + completer.completeOperation(operation, propagateCancel: false); + }, + ); }); }); @@ -406,8 +439,9 @@ void main() { 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 @@ void main() { }); CancelableOperation 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { }); 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(); - 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(); + 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 @@ void main() { 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 @@ void main() { }); CancelableOperation 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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(); - 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(); + 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 @@ void main() { late CancelableOperation operation; setUp(() { canceled1 = false; - completer1 = CancelableCompleter(onCancel: () { - canceled1 = true; - }); + completer1 = CancelableCompleter( + onCancel: () { + canceled1 = true; + }, + ); canceled2 = false; - completer2 = CancelableCompleter(onCancel: () { - canceled2 = true; - }); + completer2 = CancelableCompleter( + onCancel: () { + canceled2 = true; + }, + ); canceled3 = false; - completer3 = CancelableCompleter(onCancel: () { - canceled3 = true; - }); - - operation = CancelableOperation.race( - [completer1.operation, completer2.operation, completer3.operation]); + completer3 = CancelableCompleter( + onCancel: () { + canceled3 = true; + }, + ); + + 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 2fc1e8b74..cf4798202 100644 --- a/pkgs/async/test/chunked_stream_reader.dart +++ b/pkgs/async/test/chunked_stream_reader.dart @@ -324,10 +324,9 @@ void main() { }); 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 9729c0662..effca5be4 100644 --- a/pkgs/async/test/future_group_test.dart +++ b/pkgs/async/test/future_group_test.dart @@ -110,20 +110,22 @@ void main() { 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(); - var completer2 = Completer(); - var completer3 = Completer(); + test( + "completes to the first error to be emitted, even if it's not closed", + () { + var completer1 = Completer(); + var completer2 = Completer(); + var completer3 = Completer(); - 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 @@ void main() { 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.future.then(expectAsync1((_) { - expect(idle, isTrue); - expect(onIdleDone, isTrue); - futureFired = 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; + }), + ); var completer = Completer(); futureGroup.add(completer.future); diff --git a/pkgs/async/test/lazy_stream_test.dart b/pkgs/async/test/lazy_stream_test.dart index 9785b2e18..064a03264 100644 --- a/pkgs/async/test/lazy_stream_test.dart +++ b/pkgs/async/test/lazy_stream_test.dart @@ -12,10 +12,12 @@ import 'utils.dart'; 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 @@ 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); @@ -93,10 +97,12 @@ void main() { 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 16d69866a..79527daa1 100644 --- a/pkgs/async/test/null_stream_sink_test.dart +++ b/pkgs/async/test/null_stream_sink_test.dart @@ -58,9 +58,11 @@ void main() { 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 @@ void main() { 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); - - await future; - sink.add(1); - sink.addError('oh no'); - expect(sink.addStream(const Stream.empty()), completes); - }); + 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); + }, + ); }); }); diff --git a/pkgs/async/test/reject_errors_test.dart b/pkgs/async/test/reject_errors_test.dart index 27e3c2552..c432f23aa 100644 --- a/pkgs/async/test/reject_errors_test.dart +++ b/pkgs/async/test/reject_errors_test.dart @@ -74,8 +74,9 @@ void main() { 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 @@ void main() { var addStreamCancelled = false; transformed.addStream( - StreamController(onCancel: () => addStreamCancelled = true).stream); + StreamController(onCancel: () => addStreamCancelled = true).stream, + ); await pumpEventQueue(); expect(addStreamCancelled, isFalse); @@ -138,22 +140,27 @@ void main() { 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 4aab28712..a0c117eb6 100644 --- a/pkgs/async/test/restartable_timer_test.dart +++ b/pkgs/async/test/restartable_timer_test.dart @@ -100,7 +100,9 @@ void main() { 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 e85999e9a..4c31666e7 100644 --- a/pkgs/async/test/result/result_captureAll_test.dart +++ b/pkgs/async/test/result/result_captureAll_test.dart @@ -17,8 +17,10 @@ Result res(int n) => Result.value(n); Result err(int n) => ErrorResult('$n', someStack); /// Helper function creating an iterable of futures. -Iterable> futures(int count, - {bool Function(int index)? throwWhen}) sync* { +Iterable> futures( + int count, { + bool Function(int index)? throwWhen, +}) sync* { for (var i = 0; i < count; i++) { if (throwWhen != null && throwWhen(i)) { yield Future.error('$i', someStack); @@ -46,20 +48,23 @@ void main() { }); test('error only', () async { - var all = - await Result.captureAll(futures(1, throwWhen: (_) => true)); + var all = await Result.captureAll( + futures(1, throwWhen: (_) => true), + ); expect(all, [err(0)]); }); test('multiple error only', () async { - var all = - await Result.captureAll(futures(3, throwWhen: (_) => true)); + var all = await Result.captureAll( + futures(3, throwWhen: (_) => true), + ); expect(all, [err(0), err(1), err(2)]); }); test('mixed error and value', () async { - var all = - await Result.captureAll(futures(4, throwWhen: (x) => x.isOdd)); + var all = await Result.captureAll( + futures(4, throwWhen: (x) => x.isOdd), + ); expect(all, [res(0), err(1), res(2), err(3)]); }); @@ -185,7 +190,7 @@ void main() { Future(() => 2), 3, Future(() async => await Future.error('4', someStack)), - Future.value(5) + Future.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 0d2b9634d..311ab5c2a 100644 --- a/pkgs/async/test/result/result_flattenAll_test.dart +++ b/pkgs/async/test/result/result_flattenAll_test.dart @@ -12,8 +12,10 @@ Result res(T n) => Result.value(n); Result err(int n) => ErrorResult('$n', someStack); /// Helper function creating an iterable of results. -Iterable> results(int count, - {bool Function(int index)? throwWhen}) sync* { +Iterable> 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 @@ void main() { }); test('single error', () { expectAll( - Result.flattenAll(results(1, throwWhen: (_) => true)), err(0)); + Result.flattenAll(results(1, throwWhen: (_) => true)), + err(0), + ); }); test('multiple values', () { expectAll(Result.flattenAll(results(5)), res([0, 1, 2, 3, 4])); }); test('multiple errors', () { - expectAll(Result.flattenAll(results(5, throwWhen: (x) => x.isOdd)), - err(1)); // First error is result. + expectAll( + Result.flattenAll(results(5, throwWhen: (x) => x.isOdd)), + err(1), + ); // First error is result. }); test('error last', () { expectAll( - Result.flattenAll(results(5, throwWhen: (x) => x == 4)), err(4)); + Result.flattenAll(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 de2188403..a712e98b4 100644 --- a/pkgs/async/test/result/result_future_test.dart +++ b/pkgs/async/test/result/result_future_test.dart @@ -25,8 +25,10 @@ void main() { // 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 96620463f..65d47f9c6 100644 --- a/pkgs/async/test/result/result_test.dart +++ b/pkgs/async/test/result/result_test.dart @@ -59,11 +59,14 @@ void main() { test('complete with value', () { Result result = ValueResult(42); var c = Completer(); - 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 @@ void main() { var c = Completer(); c.future.then((bool v) { fail('Unexpected value $v'); - }).then((_) {}, onError: expectAsync2((e, s) { - expect(e, equals('BAD')); - expect(s, same(stack)); - })); + }).then( + (_) {}, + onError: expectAsync2((e, s) { + expect(e, equals('BAD')); + expect(s, same(stack)); + }), + ); result.complete(c); }); test('add sink value', () { var result = ValueResult(42); - EventSink sink = TestSink(onData: expectAsync1((v) { - expect(v, equals(42)); - })); + EventSink sink = TestSink( + onData: expectAsync1((v) { + expect(v, equals(42)); + }), + ); result.addTo(sink); }); test('add sink error', () { Result result = ErrorResult('BAD', stack); - EventSink sink = TestSink(onError: expectAsync2((e, s) { - expect(e, equals('BAD')); - expect(s, same(stack)); - })); + EventSink sink = TestSink( + onError: expectAsync2((e, s) { + expect(e, equals('BAD')); + expect(s, same(stack)); + }), + ); result.addTo(sink); }); test('value as future', () { Result result = ValueResult(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 result = ErrorResult('BAD', stack); result.asFuture.then((bool v) { fail('Unexpected value $v'); - }).then((_) {}, onError: expectAsync2((e, s) { - expect(e, equals('BAD')); - expect(s, same(stack)); - })); + }).then( + (_) {}, + onError: expectAsync2((e, s) { + expect(e, equals('BAD')); + expect(s, same(stack)); + }), + ); }); test('capture future value', () { var value = Future.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.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>.value(Result.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 @@ void main() { var future = Future>.value(Result.error('BAD', stack)); Result.release(future).then((v) { fail('Unexpected value: $v'); - }).then((_) {}, onError: expectAsync2((e, s) { - expect(e, equals('BAD')); - expect(s, same(stack)); - })); + }).then( + (_) {}, + onError: expectAsync2((e, s) { + expect(e, equals('BAD')); + expect(s, same(stack)); + }), + ); }); test('release future real error', () { @@ -165,24 +193,33 @@ void main() { var future = Future>.error('BAD', stack); Result.release(future).then((v) { fail('Unexpected value: $v'); - }).then((_) {}, onError: expectAsync2((e, s) { - expect(e, equals('BAD')); - expect(s, same(stack)); - })); + }).then( + (_) {}, + onError: expectAsync2((e, s) { + expect(e, equals('BAD')); + expect(s, same(stack)); + }), + ); }); test('capture stream', () { var c = StreamController(); 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 @@ void main() { var events = [ Result.value(42), Result.error('BAD', stack), - Result.value(37) + Result.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 @@ void main() { 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 @@ void main() { test('release stream cancel on error', () { var c = StreamController>(); 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 @@ void main() { 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 @@ class TestSink implements EventSink { 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 95b321b90..9e4281c0b 100644 --- a/pkgs/async/test/single_subscription_transformer_test.dart +++ b/pkgs/async/test/single_subscription_transformer_test.dart @@ -12,8 +12,9 @@ import 'utils.dart'; 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 @@ void main() { 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); - - var subscription = stream.listen(null); - await flushMicrotasks(); - expect(canceled, isFalse); - - subscription.cancel(); - await flushMicrotasks(); - expect(canceled, isTrue); - }); + 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); + + 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 ee324f51d..96e801ce1 100644 --- a/pkgs/async/test/sink_base_test.dart +++ b/pkgs/async/test/sink_base_test.dart @@ -18,29 +18,34 @@ void main() { // 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()); - })); + var sink = _StreamSink( + onError: expectAsync2((error, [stackTrace]) { + expect(error, equals('oh no')); + expect(stackTrace, isA()); + }), + ); 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()); - })); + onAdd: expectAsync1((value) { + expect(value, equals(123)); + }, count: 1), + onError: expectAsync2((error, [stackTrace]) { + expect(error, equals('oh no')); + expect(stackTrace, isA()); + }), + ); var controller = StreamController(); sink.addStream(controller.stream); @@ -104,25 +109,27 @@ void main() { expect(doneCompleted, isTrue); }); - test('done returns a future that completes once close() completes', - () async { - var completer = Completer(); - var sink = _StreamSink(onClose: expectAsync0(() => completer.future)); + test( + 'done returns a future that completes once close() completes', + () async { + var completer = Completer(); + 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 @@ void main() { }); 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 @@ void main() { test('writes each object in the iterable', () async { var chunks = >[]; 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 @@ void main() { test('writes separators between each object', () async { var chunks = >[]; 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 @@ void main() { 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 = >[]; 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 @@ void main() { 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 @@ void main() { }); test('locks the sink as though a stream was being added', () { - var sink = - _IOSink(onFlush: expectAsync0(() => Completer().future)); + var sink = _IOSink( + onFlush: expectAsync0(() => Completer().future), + ); sink.flush(); expect(() => sink.add([0]), throwsStateError); expect(() => sink.addError('oh no'), throwsStateError); @@ -344,11 +366,11 @@ class _StreamSink extends StreamSinkBase { final void Function(Object error, [StackTrace? stackTrace]) _onError; final FutureOr Function() _onClose; - _StreamSink( - {void Function(int value)? onAdd, - void Function(Object error, [StackTrace? stackTrace])? onError, - FutureOr Function()? onClose}) - : _onAdd = onAdd ?? ((_) {}), + _StreamSink({ + void Function(int value)? onAdd, + void Function(Object error, [StackTrace? stackTrace])? onError, + FutureOr Function()? onClose, + }) : _onAdd = onAdd ?? ((_) {}), _onError = onError ?? ((_, [__]) {}), _onClose = onClose ?? (() {}); @@ -374,13 +396,13 @@ class _IOSink extends IOSinkBase { final FutureOr Function() _onClose; final Future Function() _onFlush; - _IOSink( - {void Function(List value)? onAdd, - void Function(Object error, [StackTrace? stackTrace])? onError, - FutureOr Function()? onClose, - Future Function()? onFlush, - Encoding encoding = utf8}) - : _onAdd = onAdd ?? ((_) {}), + _IOSink({ + void Function(List value)? onAdd, + void Function(Object error, [StackTrace? stackTrace])? onError, + FutureOr Function()? onClose, + Future 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 a2bad1a9d..3f6fa26aa 100644 --- a/pkgs/async/test/stream_closer_test.dart +++ b/pkgs/async/test/stream_closer_test.dart @@ -18,12 +18,16 @@ void main() { 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.error('oh no').transform(closer).toList(), - throwsA('oh no')); + expect( + Stream.error('oh no').transform(closer).toList(), + throwsA('oh no'), + ); }); test('transforms a broadcast stream into a broadcast stream', () { @@ -53,8 +57,9 @@ void main() { test('forwards cancel', () { var isCancelled = false; - var controller = - StreamController(onCancel: () => isCancelled = true); + var controller = StreamController( + onCancel: () => isCancelled = true, + ); var transformed = controller.stream.transform(closer); expect(isCancelled, isFalse); @@ -67,8 +72,10 @@ void main() { test('forwards errors from cancel', () { var controller = StreamController(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 @@ void main() { test('the inner subscription is canceled once the closer is closed', () { var isCancelled = false; - var controller = - StreamController(onCancel: () => isCancelled = true); + var controller = StreamController( + onCancel: () => isCancelled = true, + ); expect(controller.stream.transform(closer), emitsDone); expect(closer.close(), completes); @@ -98,18 +106,24 @@ void main() { 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 @@ void main() { test( 'the underlying subscription is never listened if the stream is ' 'never listened', () async { - var controller = - StreamController(onListen: expectAsync0(() {}, count: 0)); + var controller = StreamController( + onListen: expectAsync0(() {}, count: 0), + ); controller.stream.transform(closer); expect(closer.close(), completes); @@ -134,7 +149,9 @@ void main() { 'the underlying subscription is listened and then canceled once the ' 'stream is listened', () { var controller = StreamController( - onListen: expectAsync0(() {}), onCancel: expectAsync0(() {})); + onListen: expectAsync0(() {}), + onCancel: expectAsync0(() {}), + ); var stream = controller.stream.transform(closer); expect(closer.close(), completes); @@ -143,8 +160,9 @@ void main() { }); test('Subscription.cancel() errors are silently ignored', () async { - var controller = - StreamController(onCancel: expectAsync0(() => throw 'oh no')); + var controller = StreamController( + onCancel: expectAsync0(() => throw 'oh no'), + ); var stream = controller.stream.transform(closer); expect(closer.close(), completes); @@ -166,8 +184,9 @@ void main() { 'listened', () async { expect(closer.close(), completes); - var controller = - StreamController(onListen: expectAsync0(() {}, count: 0)); + var controller = StreamController( + onListen: expectAsync0(() {}, count: 0), + ); controller.stream.transform(closer); await pumpEventQueue(); @@ -179,7 +198,9 @@ void main() { expect(closer.close(), completes); var controller = StreamController( - onListen: expectAsync0(() {}), onCancel: expectAsync0(() {})); + onListen: expectAsync0(() {}), + onCancel: expectAsync0(() {}), + ); controller.stream.transform(closer).listen(null); }); @@ -187,8 +208,9 @@ void main() { test('Subscription.cancel() errors are silently ignored', () async { expect(closer.close(), completes); - var controller = - StreamController(onCancel: expectAsync0(() => throw 'oh no')); + var controller = StreamController( + 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 f58162e47..0ef5cf4da 100644 --- a/pkgs/async/test/stream_completer_test.dart +++ b/pkgs/async/test/stream_completer_test.dart @@ -82,16 +82,18 @@ void main() { var lastEvent = -1; var controller = StreamController(); 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 @@ void main() { var completer = StreamCompleter(); completer.setEmpty(); var done = Completer(); - 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(); var done = Completer(); - 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 @@ void main() { test("source stream isn't listened to until completer stream is", () async { var completer = StreamCompleter(); 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 @@ void main() { var completer = StreamCompleter(); Object lastEvent = -1; var controller = StreamController(); - 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 @@ void main() { 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 @@ void main() { test('asFuture with error accross setting stream', () async { var completer = StreamCompleter(); var controller = StreamController(); - 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(); - 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(); - completer.setError('oh no'); - await flushMicrotasks(); + test( + 'produces a stream that emits a single error on a later listen', + () async { + var completer = StreamCompleter(); + 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 b43dedc1d..050732fda 100644 --- a/pkgs/async/test/stream_extensions_test.dart +++ b/pkgs/async/test/stream_extensions_test.dart @@ -15,36 +15,48 @@ void main() { 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 @@ void main() { 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 @@ void main() { test('cancels the subscription after an event', () async { var isCancelled = false; - var controller = StreamController(onCancel: () { - isCancelled = true; - }); + var controller = StreamController( + onCancel: () { + isCancelled = true; + }, + ); controller.add(1); await expectLater(controller.stream.firstOrNull, completion(equals(1))); @@ -83,9 +99,11 @@ void main() { test('cancels the subscription after an error', () async { var isCancelled = false; - var controller = StreamController(onCancel: () { - isCancelled = true; - }); + var controller = StreamController( + onCancel: () { + isCancelled = true; + }, + ); controller.addError('oh no'); await expectLater(controller.stream.firstOrNull, throwsA('oh no')); @@ -119,28 +137,32 @@ void main() { ..close(); }); - test('emits events added before and after the listenAndBuffer is listened', - () async { - var controller = StreamController() - ..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(); - }); + test( + 'emits events added before and after the listenAndBuffer is listened', + () async { + var controller = StreamController() + ..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(); + }, + ); test('listens as soon as listenAndBuffer() is called', () async { var listened = false; - var controller = StreamController(onListen: () { - listened = true; - }); + var controller = StreamController( + onListen: () { + listened = true; + }, + ); controller.stream.listenAndBuffer(); expect(listened, isTrue); }); @@ -160,10 +182,12 @@ void main() { test('forwards cancel', () async { var completer = Completer(); var canceled = false; - var controller = StreamController(onCancel: () { - canceled = true; - return completer.future; - }); + var controller = StreamController( + 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 7b40f6e30..ac09e9567 100644 --- a/pkgs/async/test/stream_group_test.dart +++ b/pkgs/async/test/stream_group_test.dart @@ -29,8 +29,10 @@ void main() { 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 @@ void main() { expect(streamGroup.close(), completes); var transformed = streamGroup.stream.transform( - StreamTransformer.fromHandlers( - handleError: (error, _, sink) => sink.add('error: $error'))); - expect(transformed.toList(), - completion(equals(['error: first', 'error: second']))); + StreamTransformer.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 @@ void main() { expect(streamGroup.close(), completes); var transformed = streamGroup.stream.transform( - StreamTransformer.fromHandlers( - handleData: (data, sink) => sink.add('data: $data'), - handleError: (error, _, sink) => sink.add('error: $error'))); + StreamTransformer.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 @@ void main() { 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 @@ void main() { 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 @@ void main() { var subscription = streamGroup.stream.listen(null); var completer = Completer(); - var controller = - StreamController(onCancel: () => completer.future); + var controller = StreamController( + onCancel: () => completer.future, + ); streamGroup.add(controller.stream); await flushMicrotasks(); @@ -187,7 +203,9 @@ void main() { var paused = false; var controller = StreamController( - onPause: () => paused = true, onResume: () => paused = false); + onPause: () => paused = true, + onResume: () => paused = false, + ); subscription.pause(); await flushMicrotasks(); @@ -210,12 +228,15 @@ void main() { test('immediately listens to and cancels the stream', () async { var listened = false; var canceled = false; - var controller = StreamController(onListen: () { - listened = true; - }, onCancel: expectAsync0(() { - expect(listened, isTrue); - canceled = true; - })); + var controller = StreamController( + onListen: () { + listened = true; + }, + onCancel: expectAsync0(() { + expect(listened, isTrue); + canceled = true; + }), + ); streamGroup.add(controller.stream); await flushMicrotasks(); @@ -224,16 +245,18 @@ void main() { }); test('forwards cancel errors', () { - var controller = - StreamController(onCancel: () => throw 'error'); + var controller = StreamController( + onCancel: () => throw 'error', + ); expect(streamGroup.add(controller.stream), throwsA('error')); }); test('forwards a cancel future', () async { var completer = Completer(); - var controller = - StreamController(onCancel: () => completer.future); + var controller = StreamController( + onCancel: () => completer.future, + ); var fired = false; streamGroup.add(controller.stream)!.then((_) => fired = true); @@ -260,21 +283,24 @@ void main() { // 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(onCancel: () => firstCancelled = true); + var first = StreamController( + onCancel: () => firstCancelled = true, + ); streamGroup.add(first.stream); streamGroup.add(alreadyListened); var lastCancelled = false; - var last = - StreamController(onCancel: () => lastCancelled = true); + var last = StreamController( + onCancel: () => lastCancelled = true, + ); streamGroup.add(last.stream); runZonedGuarded(() => streamGroup.stream.listen(null), (_, __) {}); @@ -290,8 +316,9 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { expect(streamGroup.close(), completes); }); - test("doesn't buffer events once a listener has been added and removed", - () async { - var controller = StreamController(); - streamGroup.add(controller.stream); + test( + "doesn't buffer events once a listener has been added and removed", + () async { + var controller = StreamController(); + 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.broadcast(); @@ -390,7 +424,9 @@ void main() { 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 @@ void main() { test('never cancels single-subscription streams', () async { var subscription = streamGroup.stream.listen(null); - var controller = - StreamController(onCancel: expectAsync0(() {}, count: 0)); + var controller = StreamController( + onCancel: expectAsync0(() {}, count: 0), + ); streamGroup.add(controller.stream); await flushMicrotasks(); @@ -451,29 +488,31 @@ void main() { 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(); - streamGroup.add(controller.stream); - await flushMicrotasks(); + var controller = StreamController(); + 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(); @@ -492,21 +531,23 @@ void main() { 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 @@ void main() { var controller1 = StreamController(); var controller2 = StreamController(); - 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 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { group('add()', () { group('while dormant', () { - test("doesn't listen to the stream until the group is listened to", - () async { - var controller = StreamController(); + test( + "doesn't listen to the stream until the group is listened to", + () async { + var controller = StreamController(); - 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(); @@ -631,27 +676,29 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { expect(streamGroup.remove(controller.stream), isNull); }); - test('and closed closes the group when the last stream is removed', - () async { - var controller1 = StreamController(); - var controller2 = StreamController(); + test( + 'and closed closes the group when the last stream is removed', + () async { + var controller1 = StreamController(); + var controller2 = StreamController(); - 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 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { }); test('forwards cancel errors', () async { - var controller = - StreamController(onCancel: () => throw 'error'); + var controller = StreamController( + onCancel: () => throw 'error', + ); streamGroup.add(controller.stream); streamGroup.stream.listen(null); @@ -697,8 +745,9 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { test('forwards cancel futures', () async { var completer = Completer(); - var controller = - StreamController(onCancel: () => completer.future); + var controller = StreamController( + onCancel: () => completer.future, + ); streamGroup.stream.listen(null); await flushMicrotasks(); @@ -725,29 +774,31 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { 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(); - var controller2 = StreamController(); + var controller1 = StreamController(); + var controller2 = StreamController(); - 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 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { 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(); + 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(); - var controller2 = StreamController(); + var controller1 = StreamController(); + var controller2 = StreamController(); - streamGroup.add(controller1.stream); - streamGroup.add(controller2.stream); - await flushMicrotasks(); + streamGroup.add(controller1.stream); + streamGroup.add(controller2.stream); + await flushMicrotasks(); - streamGroup.close(); - await flushMicrotasks(); - expect(done, isFalse); + streamGroup.close(); + await flushMicrotasks(); + expect(done, isFalse); - controller1.close(); - await flushMicrotasks(); - expect(done, isFalse); + controller1.close(); + await flushMicrotasks(); + expect(done, isFalse); - controller2.close(); - await flushMicrotasks(); - expect(done, isTrue); - }); + 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(); - streamGroup.add(controller.stream); - await flushMicrotasks(); + test( + 'returns a Future that completes once all events are dispatched', + () async { + var events = []; + streamGroup.stream.listen(events.add); - // 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(); + var controller = StreamController(); + streamGroup.add(controller.stream); + await flushMicrotasks(); - await streamGroup.close(); - expect(events, equals(['one', 'two', 'three', 'four', 'five', 'six'])); - }); + // 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 @@ void regardlessOfType(StreamGroup Function() newStreamGroup) { 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.stream.drain().then(expectAsync1((_) { - expect(idle, isTrue); - expect(onIdleDone, isFalse); - streamClosed = 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; + }), + ); var controller = StreamController(); streamGroup.add(controller.stream); diff --git a/pkgs/async/test/stream_queue_test.dart b/pkgs/async/test/stream_queue_test.dart index cd4433aec..48ebf3c06 100644 --- a/pkgs/async/test/stream_queue_test.dart +++ b/pkgs/async/test/stream_queue_test.dart @@ -153,8 +153,12 @@ void main() { test('multiple requests at the same time', () async { var events = StreamQueue(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 @@ void main() { 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 @@ void main() { }); test('multiple requests at the same time', () async { var events = StreamQueue(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 @@ void main() { expect(() => events.cancel(), throwsStateError); }); - test('cancels underlying subscription when called before any event', - () async { - var cancelFuture = Future.value(42); - var controller = StreamController(onCancel: () => cancelFuture); - var events = StreamQueue(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(onCancel: () => cancelFuture); + var events = StreamQueue(controller.stream); + expect(await events.cancel(), 42); + }, + ); test('cancels underlying subscription, returns result', () async { var cancelFuture = Future.value(42); @@ -523,14 +534,16 @@ void main() { expect(controller.hasListener, isFalse); }); - test('cancels the underlying subscription when called before any event', - () async { - var cancelFuture = Future.value(42); - var controller = StreamController(onCancel: () => cancelFuture); + test( + 'cancels the underlying subscription when called before any event', + () async { + var cancelFuture = Future.value(42); + var controller = StreamController(onCancel: () => cancelFuture); - var events = StreamQueue(controller.stream); - expect(await events.cancel(immediate: true), 42); - }); + var events = StreamQueue(controller.stream); + expect(await events.cancel(immediate: true), 42); + }, + ); test('closes pending requests', () async { var events = StreamQueue(createStream()); @@ -541,27 +554,33 @@ void main() { await events.cancel(immediate: true); }); - test('returns the result of closing the underlying subscription', - () async { - var controller = - StreamController(onCancel: () => Future.value(42)); - var events = StreamQueue(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(onListen: () => wasListened = true); - var events = StreamQueue(controller.stream); - expect(wasListened, isFalse); - expect(controller.hasListener, isFalse); + test( + 'returns the result of closing the underlying subscription', + () async { + var controller = StreamController( + onCancel: () => Future.value(42), + ); + var events = StreamQueue(controller.stream); + expect(await events.cancel(immediate: true), 42); + }, + ); - await events.cancel(immediate: true); - expect(wasListened, isTrue); - 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( + onListen: () => wasListened = true, + ); + var events = StreamQueue(controller.stream); + expect(wasListened, isFalse); + expect(controller.hasListener, isFalse); + + await events.cancel(immediate: true); + expect(wasListened, isTrue); + expect(controller.hasListener, isFalse); + }, + ); }); }); @@ -854,22 +873,26 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { // 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 @@ void main() { } } // 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 3a6f25bcc..aa8447fb2 100644 --- a/pkgs/async/test/stream_sink_completer_test.dart +++ b/pkgs/async/test/stream_sink_completer_test.dart @@ -79,9 +79,11 @@ void main() { 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 @@ void main() { 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(); @@ -235,27 +239,31 @@ void main() { }); }); - 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 caea3495e..9b4371898 100644 --- a/pkgs/async/test/stream_sink_transformer_test.dart +++ b/pkgs/async/test/stream_sink_transformer_test.dart @@ -18,15 +18,21 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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 27921db1d..ff916b291 100644 --- a/pkgs/async/test/stream_splitter_test.dart +++ b/pkgs/async/test/stream_splitter_test.dart @@ -17,27 +17,29 @@ void main() { splitter = StreamSplitter(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 @@ void main() { 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(); - - var branch = splitter.split(); - splitter.close(); + test( + "a branch that's created in the middle of a stream replays it", + () async { + controller.add(1); + controller.add(2); + await flushMicrotasks(); - controller.add(3); - controller.add(4); - controller.close(); + var branch = splitter.split(); + splitter.close(); - expect(branch.toList(), completion(equals([1, 2, 3, 4]))); - }); + controller.add(3); + controller.add(4); + controller.close(); - 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(branch.toList(), completion(equals([1, 2, 3, 4]))); + }, + ); - expect(splitter.split().toList(), completion(equals([1, 2, 3]))); - splitter.close(); - }); + 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(); + }, + ); 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 147d419c0..69066ba64 100644 --- a/pkgs/async/test/stream_zip_test.dart +++ b/pkgs/async/test/stream_zip_test.dart @@ -39,76 +39,94 @@ void main() { void testZip(Iterable 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 @@ void main() { testZip([ mks([1, 2, 3]), mks([]), - mks([7, 8, 9]) + mks([7, 8, 9]), ], []); }); @@ -124,7 +142,7 @@ void main() { testZip([ mks([1, 2, 3]), mks([4, 5, 6]), - mks([]) + mks([]), ], []); }); @@ -133,30 +151,34 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { ..add(9); // Transformer that puts error into controller when one of the first two // streams have sent a done event. - var trans = - StreamTransformer.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.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 @@ void main() { 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.delayed(const Duration(milliseconds: 25))); - } else if (ctr == 2) { - sub.pause(); - Future.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.delayed(const Duration(milliseconds: 25))); + } else if (ctr == 2) { + sub.pause(); + Future.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 a18c7761e..f36f7edff 100644 --- a/pkgs/async/test/stream_zip_zone_test.dart +++ b/pkgs/async/test/stream_zip_zone_test.dart @@ -17,7 +17,10 @@ void main() { testStream('broadcast-async', controller, controller.stream); controller = StreamController(); 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 @@ void main() { 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 @@ void testStream(String name, StreamController controller, Stream stream) { 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 acdbdf139..9081b6071 100644 --- a/pkgs/async/test/subscription_stream_test.dart +++ b/pkgs/async/test/subscription_stream_test.dart @@ -79,16 +79,22 @@ void main() { var cancelCompleter = Completer(); var source = createErrorStream(cancelCompleter); onCancel = cancelCompleter.future; - var sourceSubscription = - source.listen(null, cancelOnError: sourceCancels); + var sourceSubscription = source.listen( + null, + cancelOnError: sourceCancels, + ); subscriptionStream = SubscriptionStream(sourceSubscription); }); test('- subscriptionStream: no', () async { var done = Completer(); 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 @@ void main() { test('- subscriptionStream: yes', () async { var completer = Completer(); var events = []; - 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 53610e19f..1ca6a429b 100644 --- a/pkgs/async/test/subscription_transformer_test.dart +++ b/pkgs/async/test/subscription_transformer_test.dart @@ -14,19 +14,22 @@ void main() { test('forwards cancellation', () async { var isCanceled = false; var cancelCompleter = Completer(); - var controller = - StreamController(onCancel: expectAsync0>(() { - isCanceled = true; - return cancelCompleter.future; - })); + var controller = StreamController( + onCancel: expectAsync0>(() { + 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 @@ void main() { 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 @@ void main() { var completer = Completer(); var controller = StreamController(); 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 @@ void main() { var pauseCount = 0; var controller = StreamController(); 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 @@ void main() { expect(pauseCount, equals(3)); }); - test("doesn't invoke the callback when the subscription has been canceled", - () async { - var controller = StreamController(); - var subscription = controller.stream - .transform(subscriptionTransformer( - handlePause: expectAsync1((_) {}, count: 0))) - .listen(expectAsync1((_) {}, count: 0)); - - subscription.cancel(); - subscription.pause(); - subscription.pause(); - subscription.pause(); - }); + test( + "doesn't invoke the callback when the subscription has been canceled", + () async { + var controller = StreamController(); + var subscription = controller.stream + .transform( + subscriptionTransformer( + handlePause: expectAsync1((_) {}, count: 0), + ), + ) + .listen(expectAsync1((_) {}, count: 0)); + + subscription.cancel(); + subscription.pause(); + subscription.pause(); + subscription.pause(); + }, + ); }); group('with a resume callback', () { @@ -186,11 +209,14 @@ void main() { var resumeCount = 0; var controller = StreamController(); 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 @@ void main() { var resumed = false; var controller = StreamController(); 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(); subscription.pause(completer.future); @@ -233,19 +262,24 @@ void main() { expect(resumed, isTrue); }); - test("doesn't invoke the callback when the subscription has been canceled", - () async { - var controller = StreamController(); - var subscription = controller.stream - .transform(subscriptionTransformer( - handlePause: expectAsync1((_) {}, count: 0))) - .listen(expectAsync1((_) {}, count: 0)); - - subscription.cancel(); - subscription.resume(); - subscription.resume(); - subscription.resume(); - }); + test( + "doesn't invoke the callback when the subscription has been canceled", + () async { + var controller = StreamController(); + var subscription = controller.stream + .transform( + subscriptionTransformer( + handlePause: expectAsync1((_) {}, count: 0), + ), + ) + .listen(expectAsync1((_) {}, count: 0)); + + subscription.cancel(); + subscription.resume(); + subscription.resume(); + subscription.resume(); + }, + ); }); group('when the outer subscription is canceled but the inner is not', () { @@ -254,10 +288,13 @@ void main() { var controller = StreamController(); 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 74195bab5..5eaf8de6d 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 @@ void main() { late bool isCanceled; setUp(() { isCanceled = false; - controller = StreamController(onCancel: () { - isCanceled = true; - }); + controller = StreamController( + onCancel: () { + isCanceled = true; + }, + ); wrapper = TypeSafeStreamSubscription(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 @@ void main() { late bool isCanceled; setUp(() { isCanceled = false; - controller = StreamController(onCancel: () { - isCanceled = true; - }); + controller = StreamController( + onCancel: () { + isCanceled = true; + }, + ); wrapper = TypeSafeStreamSubscription(controller.stream.listen(null)); }); @@ -85,8 +93,9 @@ void main() { // TODO(nweiz): Use the wrapper declared in setUp when sdk#26226 is // fixed. controller = StreamController(); - wrapper = - TypeSafeStreamSubscription(controller.stream.listen(null)); + wrapper = TypeSafeStreamSubscription( + controller.stream.listen(null), + ); wrapper.onData(expectAsync1((_) {}, count: 0)); controller.add('foo'); @@ -96,9 +105,11 @@ void main() { 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 0a6b339ac..be9ad67ec 100644 --- a/pkgs/async/test/utils.dart +++ b/pkgs/async/test/utils.dart @@ -26,15 +26,16 @@ OptionalArgAction unreachable(String name) => 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 @@ final throwsTypeError = throwsA(isA()); /// Can be used to test cases where a stream should not be used. class UnusableStream extends Stream { @override - StreamSubscription listen(void Function(T event)? onData, - {Function? onError, void Function()? onDone, bool? cancelOnError}) { + StreamSubscription listen( + void Function(T event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { throw UnimplementedError('Gotcha!'); } } From bdf4633cbd5f870c74796a0c11448cd9db2a6cd1 Mon Sep 17 00:00:00 2001 From: Moritz Date: Thu, 24 Apr 2025 08:21:16 +0200 Subject: [PATCH 2/4] Format other packages as well --- pkgs/characters/benchmark/benchmark.dart | 6 +- pkgs/characters/lib/src/characters_impl.dart | 82 +- .../lib/src/grapheme_clusters/breaks.dart | 42 +- pkgs/characters/test/breaks_test.dart | 52 +- pkgs/characters/test/characters_test.dart | 102 +- pkgs/characters/test/src/equiv.dart | 14 +- pkgs/characters/test/src/unicode_tests.dart | 6 +- pkgs/characters/test/src/various_tests.dart | 2 +- pkgs/characters/tool/benchmark.dart | 26 +- pkgs/characters/tool/bin/generate_tables.dart | 166 +++- pkgs/characters/tool/bin/generate_tests.dart | 53 +- pkgs/characters/tool/generate.dart | 27 +- pkgs/characters/tool/src/args.dart | 19 +- pkgs/characters/tool/src/atsp.dart | 2 +- .../tool/src/automaton_builder.dart | 432 ++++++--- pkgs/characters/tool/src/data_files.dart | 45 +- .../tool/src/grapheme_category_loader.dart | 143 ++- pkgs/characters/tool/src/shared.dart | 19 +- .../tool/src/string_literal_writer.dart | 9 +- pkgs/characters/tool/src/table_builder.dart | 6 +- .../benchmark/deep_collection_equality.dart | 12 +- pkgs/collection/lib/src/algorithms.dart | 216 +++-- pkgs/collection/lib/src/boollist.dart | 20 +- .../collection/lib/src/canonicalized_map.dart | 55 +- .../src/combined_wrappers/combined_map.dart | 3 +- pkgs/collection/lib/src/equality.dart | 45 +- pkgs/collection/lib/src/equality_map.dart | 14 +- pkgs/collection/lib/src/equality_set.dart | 14 +- pkgs/collection/lib/src/functions.dart | 33 +- .../lib/src/iterable_extensions.dart | 36 +- pkgs/collection/lib/src/iterable_zip.dart | 7 +- pkgs/collection/lib/src/list_extensions.dart | 90 +- pkgs/collection/lib/src/priority_queue.dart | 5 +- pkgs/collection/lib/src/queue_list.dart | 5 +- pkgs/collection/test/algorithms_test.dart | 94 +- pkgs/collection/test/boollist_test.dart | 5 +- .../test/canonicalized_map_test.dart | 82 +- .../test/combined_wrapper/iterable_test.dart | 10 +- .../test/combined_wrapper/list_test.dart | 12 +- .../test/combined_wrapper/map_test.dart | 12 +- pkgs/collection/test/comparators_test.dart | 74 +- pkgs/collection/test/equality_set_test.dart | 10 +- pkgs/collection/test/equality_test.dart | 42 +- pkgs/collection/test/extensions_test.dart | 797 ++++++++++------ pkgs/collection/test/functions_test.dart | 335 ++++--- .../test/ignore_ascii_case_test.dart | 14 +- pkgs/collection/test/iterable_zip_test.dart | 260 ++--- pkgs/collection/test/priority_queue_test.dart | 44 +- pkgs/collection/test/queue_list_test.dart | 55 +- pkgs/collection/test/union_set_test.dart | 6 +- .../test/unmodifiable_collection_test.dart | 116 ++- pkgs/collection/test/wrapper_test.dart | 136 ++- pkgs/convert/lib/src/codepage.dart | 122 ++- .../lib/src/fixed_datetime_formatter.dart | 39 +- pkgs/convert/lib/src/hex/decoder.dart | 19 +- pkgs/convert/lib/src/hex/encoder.dart | 7 +- pkgs/convert/lib/src/percent/decoder.dart | 30 +- pkgs/convert/lib/src/percent/encoder.dart | 7 +- pkgs/convert/lib/src/utils.dart | 9 +- pkgs/convert/test/codepage_test.dart | 17 +- .../test/fixed_datetime_formatter_test.dart | 105 +- pkgs/convert/test/hex_test.dart | 153 +-- pkgs/convert/test/percent_test.dart | 129 +-- pkgs/crypto/lib/src/hash_sink.dart | 26 +- pkgs/crypto/lib/src/md5.dart | 13 +- pkgs/crypto/lib/src/sha1.dart | 11 +- pkgs/crypto/lib/src/sha256.dart | 60 +- pkgs/crypto/lib/src/sha512_fastsinks.dart | 73 +- pkgs/crypto/lib/src/sha512_slowsinks.dart | 164 ++-- pkgs/crypto/test/hmac_md5_test.dart | 8 +- pkgs/crypto/test/hmac_sha1_test.dart | 8 +- pkgs/crypto/test/hmac_sha256_test.dart | 8 +- pkgs/crypto/test/hmac_sha2_test.dart | 24 +- pkgs/crypto/test/sha1_test.dart | 25 +- pkgs/crypto/test/sha256_test.dart | 69 +- pkgs/crypto/test/sha512_test.dart | 51 +- pkgs/fixnum/lib/src/int64.dart | 36 +- pkgs/fixnum/test/int32_test.dart | 72 +- pkgs/fixnum/test/int64_test.dart | 642 +++++++++---- pkgs/fixnum/test/int_64_vm_test.dart | 54 +- pkgs/lints/tool/gen_docs.dart | 9 +- pkgs/lints/tool/validate_lib.dart | 11 +- pkgs/logging/lib/src/level.dart | 2 +- pkgs/logging/lib/src/log_record.dart | 12 +- pkgs/logging/lib/src/logger.dart | 32 +- pkgs/logging/test/logging_test.dart | 190 ++-- pkgs/os_detect/bin/os_detect.dart | 6 +- pkgs/os_detect/lib/src/os_override.dart | 37 +- pkgs/os_detect/lib/src/osid_html.dart | 6 +- pkgs/os_detect/lib/src/osid_io.dart | 5 +- pkgs/os_detect/lib/src/osid_unknown.dart | 39 +- pkgs/path/benchmark/benchmark.dart | 4 +- pkgs/path/lib/path.dart | 105 +- pkgs/path/lib/src/context.dart | 116 ++- pkgs/path/lib/src/parsed_path.dart | 32 +- pkgs/path/lib/src/path_map.dart | 15 +- pkgs/path/lib/src/path_set.dart | 15 +- pkgs/path/lib/src/style/windows.dart | 11 +- pkgs/path/test/browser_test.dart | 10 +- pkgs/path/test/io_test.dart | 106 ++- pkgs/path/test/posix_test.dart | 359 +++++-- pkgs/path/test/url_test.dart | 899 ++++++++++++------ pkgs/path/test/utils.dart | 50 +- pkgs/path/test/windows_test.dart | 482 +++++++--- .../lib/src/testing/fake_platform.dart | 3 +- pkgs/platform/test/fake_platform_test.dart | 8 +- pkgs/typed_data/lib/src/typed_buffer.dart | 6 +- pkgs/typed_data/lib/src/typed_queue.dart | 22 +- pkgs/typed_data/test/queue_test.dart | 103 +- pkgs/typed_data/test/typed_buffers_test.dart | 36 +- .../test/typed_buffers_vm_test.dart | 5 +- 111 files changed, 5641 insertions(+), 2988 deletions(-) diff --git a/pkgs/characters/benchmark/benchmark.dart b/pkgs/characters/benchmark/benchmark.dart index d1f08a30b..03338a257 100644 --- a/pkgs/characters/benchmark/benchmark.dart +++ b/pkgs/characters/benchmark/benchmark.dart @@ -66,8 +66,10 @@ int replaceStrings() { 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 39a3b5d50..e8694339f 100644 --- a/pkgs/characters/lib/src/characters_impl.dart +++ b/pkgs/characters/lib/src/characters_impl.dart @@ -30,19 +30,26 @@ final class StringCharacters extends Iterable implements Characters { 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 @@ final class StringCharacters extends Iterable implements Characters { } @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 @@ final class StringCharacters extends Iterable implements Characters { 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 @@ class StringCharacterRange implements CharacterRange { 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 @@ class StringCharacterRange implements CharacterRange { 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 @@ class StringCharacterRange implements CharacterRange { 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 @@ class StringCharacterRange implements CharacterRange { 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 @@ class StringCharacterRange implements CharacterRange { } } -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 @@ int _indexOf(String source, String pattern, int start, int end) { 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 @@ int _lastIndexOf(String source, String pattern, int start, int end) { 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 0e69b6aa1..4e8c9e8d6 100644 --- a/pkgs/characters/lib/src/grapheme_clusters/breaks.dart +++ b/pkgs/characters/lib/src/grapheme_clusters/breaks.dart @@ -260,11 +260,14 @@ class BackBreaks { 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 @@ int previousBreak(String text, int start, int end, int index) { } } return BackBreaks( - text, cursorBefore, start, moveBack(stateEoTNoBreak, category)) - .nextBreak(); + text, + cursorBefore, + start, + moveBack(stateEoTNoBreak, category), + ).nextBreak(); } return index; } @@ -399,18 +405,24 @@ int nextBreak(String text, int start, int end, int index) { 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/test/breaks_test.dart b/pkgs/characters/test/breaks_test.dart index b48c8cbd4..634b07265 100644 --- a/pkgs/characters/test/breaks_test.dart +++ b/pkgs/characters/test/breaks_test.dart @@ -74,8 +74,11 @@ void main() { 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 @@ void main() { } } 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { } } 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 @@ void main() { 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 @@ void main() { } } 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 @@ void main() { // 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 7dae8fa98..d259cbcab 100644 --- a/pkgs/characters/test/characters_test.dart +++ b/pkgs/characters/test/characters_test.dart @@ -70,8 +70,13 @@ void main([List? args]) { 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 @@ void tests() { 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 @@ void tests() { }); }); 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 @@ void expectGC(Characters actual, List expected) { 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 @@ void expectGC(Characters actual, List expected) { 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 @@ void testParts( 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 hanv = gc('\u1160'); // Hangul V, Jungseong Filler. 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 705167e83..9a2afd114 100644 --- a/pkgs/characters/test/src/equiv.dart +++ b/pkgs/characters/test/src/equiv.dart @@ -35,9 +35,10 @@ class Equivalence { /// if [allowCollapse] is `false` an error is raised, and /// If [allowCollapse] is `true` the equivalence classes are /// collapsed. - Equivalence(Iterable> equivalenceClasses, - {bool allowCollapse = false}) - : _equivalences = [], + Equivalence( + Iterable> equivalenceClasses, { + bool allowCollapse = false, + }) : _equivalences = [], _class = {} { for (var eqClass in equivalenceClasses) { var newClass = _equivalences.length; @@ -49,8 +50,11 @@ class Equivalence { } 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 f88ba26b6..5c01dda8f 100644 --- a/pkgs/characters/test/src/unicode_tests.dart +++ b/pkgs/characters/test/src/unicode_tests.dart @@ -20,8 +20,10 @@ export 'unicode_grapheme_tests.dart'; /// can be compared to the original tests.) String testDescription(List 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 7409c5b0a..643facce2 100644 --- a/pkgs/characters/test/src/various_tests.dart +++ b/pkgs/characters/test/src/various_tests.dart @@ -9,6 +9,6 @@ const zalgo = [ 'L̠ͨͧͩ͘', 'G̴̻͈͍͔̹̑͗̎̅͛́', 'Ǫ̵̹̻̝̳͂̌̌͘', - '!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞' + '!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞', ], ]; diff --git a/pkgs/characters/tool/benchmark.dart b/pkgs/characters/tool/benchmark.dart index fd1170b06..a77b811e5 100644 --- a/pkgs/characters/tool/benchmark.dart +++ b/pkgs/characters/tool/benchmark.dart @@ -34,8 +34,10 @@ void main(List args) { } 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 @@ int benchForward(String text, int i, int cp, int cu) { 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 @@ int benchBackward(String text, int i, int cp, int cu) { 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 709fd0817..f348276cf 100644 --- a/pkgs/characters/tool/bin/generate_tables.dart +++ b/pkgs/characters/tool/bin/generate_tables.dart @@ -84,11 +84,18 @@ void main(List args) async { } } - var categories = - await loadCategories(update: flags.update, verbose: flags.verbose); - - generateTables(output, categories, - dryrun: flags.dryrun, verbose: flags.verbose, optimize: flags.optimize); + var categories = await loadCategories( + update: flags.update, + verbose: flags.verbose, + ); + + generateTables( + output, + categories, + dryrun: flags.dryrun, + verbose: flags.verbose, + optimize: flags.optimize, + ); } void generateTables( @@ -103,7 +110,10 @@ void generateTables( 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 @@ void generateTables( 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 @@ void generateTables( 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 @@ void generateTables( } 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 @@ void generateTables( // ----------------------------------------------------------------------------- // 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 data, - {required bool verbose}) { +void _writeStringLiteral( + StringSink out, + String name, + List data, { + required bool verbose, +}) { var prefix = 'const String $name = '; out.write(prefix); var writer = StringLiteralWriter(out, padding: 4, escape: _needsEscape); @@ -231,18 +272,38 @@ bool _needsEscape(int codeUnit) => 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 @@ int $name(int codeUnit) { } '''; -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 @@ int $name(int lead, int tail) { } // ----------------------------------------------------------------------------- -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 @@ bool _validate(Uint8List table, IndirectTable indirectTable, int lowChunkSize, [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 @@ bool _validate(Uint8List table, IndirectTable indirectTable, int lowChunkSize, [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 @@ bool _validate(Uint8List table, IndirectTable indirectTable, int lowChunkSize, } 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 2f3b67b5a..71f7860dc 100644 --- a/pkgs/characters/tool/bin/generate_tests.dart +++ b/pkgs/characters/tool/bin/generate_tests.dart @@ -46,22 +46,32 @@ void main(List args) async { 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 texts, Uint8List categories, - {bool verbose = false, bool dryrun = false}) { +void generateTests( + File? output, + List 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 @@ void generateTests(File? output, List texts, Uint8List categories, // Example character of a category which is in the lower planes. var lowerChars = List.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 generateTests(File? output, List texts, Uint8List categories, } } -void writeTests(StringSink buffer, List texts, Uint8List categories, - List lowerChars, List upperChars, - {bool dryrun = false, bool verbose = defaultVerbose}) async { +void writeTests( + StringSink buffer, + List texts, + Uint8List categories, + List lowerChars, + List upperChars, { + bool dryrun = false, + bool verbose = defaultVerbose, +}) async { var writer = StringLiteralWriter(buffer, lineLength: 9999, escape: _escape); void writeParts(List> parts, String description) { buffer.writeln(' ['); @@ -167,8 +190,12 @@ void writeTestHeader(StringSink buffer, String testName) { ..writeln(' = ['); } -void writeOtherCategories(StringSink output, Uint8List categories, - List lowerChars, List upperChars) { +void writeOtherCategories( + StringSink output, + Uint8List categories, + List lowerChars, + List 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 2eadd334b..8536d83a2 100644 --- a/pkgs/characters/tool/generate.dart +++ b/pkgs/characters/tool/generate.dart @@ -16,8 +16,12 @@ import 'src/shared.dart'; /// 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 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 @@ void main(List args) async { 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 73b6c5e14..db4264262 100644 --- a/pkgs/characters/tool/src/args.dart +++ b/pkgs/characters/tool/src/args.dart @@ -15,8 +15,12 @@ typedef Flags = ({ File? targetFile, }); -Flags parseArgs(List args, String toolName, - {bool allowOptimize = false, bool allowFile = true}) { +Flags parseArgs( + List args, + String toolName, { + bool allowOptimize = false, + bool allowFile = true, +}) { var update = false; var dryrun = false; var verbose = false; @@ -27,16 +31,19 @@ Flags parseArgs(List args, String toolName, if (arg == '-h' || arg == '--help') { stderr ..writeln( - "Usage: $toolName.dart [-u] ${allowOptimize ? "[-i|-o] " : ""}[-n]" - "${allowFile ? " " : ""}") + "Usage: $toolName.dart [-u] ${allowOptimize ? "[-i|-o] " : ""}[-n]" + "${allowFile ? " " : ""}", + ) ..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 5141caf35..43d67bcc8 100644 --- a/pkgs/characters/tool/src/atsp.dart +++ b/pkgs/characters/tool/src/atsp.dart @@ -113,7 +113,7 @@ bool opt3(Graph graph, List cycle) { 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 f8099e0de..2dd07929e 100644 --- a/pkgs/characters/tool/src/automaton_builder.dart +++ b/pkgs/characters/tool/src/automaton_builder.dart @@ -61,22 +61,28 @@ CReg:!CR !Brk !Otr Otr Otr $LARe!Pic !Brk !Pre !L !V !T !V !T !InC 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { // 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { // 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { }, 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { } 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 @@ void writeForwardAutomaton(StringSink buffer, {required bool verbose}) { // 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), + ); + transition( + state, + categoryLVT, + stateT, + !(neverBreakBefore || state == stateL), + ); transition( - state, categoryLV, stateV, !(neverBreakBefore || state == stateL)); + state, + categoryV, + stateV, + !(neverBreakBefore || state == stateL || state == stateV), + ); 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, + 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { 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 writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { // 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { } 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { 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 @@ void writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { 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 writeBackwardAutomaton(StringSink buffer, {required bool verbose}) { } 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 @@ void _writeBackTable(Uint16List table, int automatonRowLength) { /// 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 categoryNames, - int ignoreState) { + Uint16List table, + int automatonRowLength, + int stateLimit, // A multiple of automatonRowLength + String Function(int) stateNames, + String Function(int) lookaheadStateNames, + List 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 090b6b813..529883177 100644 --- a/pkgs/characters/tool/src/data_files.dart +++ b/pkgs/characters/tool/src/data_files.dart @@ -9,27 +9,34 @@ import 'shared.dart' as util; // 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 @@ class DataFile { /// and written to the [targetLocation] file. Future 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 @@ class DataFile { 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 0def73a4e..1f436f80f 100644 --- a/pkgs/characters/tool/src/grapheme_category_loader.dart +++ b/pkgs/characters/tool/src/grapheme_category_loader.dart @@ -15,11 +15,13 @@ import 'debug_names.dart'; /// Loads all categories by combining the categories of the /// grapheme break property with the categories of the InCB property. -Future loadCategories( - {bool update = false, bool verbose = false}) async { +Future 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 @@ Future loadCategories( 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 @@ Future loadCategories( /// Loads and parses the grapheme break categories from the grapheme break data, /// emoji data, and adds unpaired surrogates as controls. -Future loadGraphemeCategories( - {bool update = false, bool verbose = false}) async { +Future 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 @@ Future loadGraphemeCategories( // 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 ..\n'), + 'D800..DFFF ; Control # Cc ..\n', + ), ]); var table = _parseCategories(dataFiles, verbose: verbose); return table; } /// Loads and parses the InCB categories from the derived properties data. -Future loadInCBCategories( - {bool update = false, bool verbose = false}) async { +Future 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 @@ void _logIntersection(Uint8List table, Uint8List incbTable) { 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 @@ Uint8List _parseCategories(List files, {required bool verbose}) { var count = 0; var categoryCount = {}; var categoryMin = { - 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 @@ Uint8List _parseCategories(List files, {required bool verbose}) { 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 @@ Uint8List _parseCategories(List files, {required bool verbose}) { // 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 @@ Uint8List _parseInCBCategories(String file, {required bool verbose}) { 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 @@ Uint8List _parseInCBCategories(String file, {required bool verbose}) { } 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 @@ class UnicodePropertyTable { 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 @@ class UnicodePropertyTable { 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 @@ final class _ValueEntry extends _TableEntry { @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 @@ final class _ListEntry extends _TableEntry { @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 69ccb97ca..136cb8c8d 100644 --- a/pkgs/characters/tool/src/shared.dart +++ b/pkgs/characters/tool/src/shared.dart @@ -17,8 +17,11 @@ import 'data_files.dart'; /// /// If [targetFile] is omitted, a file in the system temporary directory /// is used instead. -Future fetch(String location, - {File? targetFile, bool forceLoad = false}) async { +Future 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 @@ Future checkLicense(bool acceptLicenseChange) async { 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 @@ void writeHeader(StringSink output, List dependencies) { } 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 @@ Directory _findRootDir() { 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 52a62d15c..9259b4eac 100644 --- a/pkgs/characters/tool/src/string_literal_writer.dart +++ b/pkgs/characters/tool/src/string_literal_writer.dart @@ -16,9 +16,12 @@ class StringLiteralWriter { static final Map _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 d407f4afb..4a49d4548 100644 --- a/pkgs/characters/tool/src/table_builder.dart +++ b/pkgs/characters/tool/src/table_builder.dart @@ -22,8 +22,10 @@ void chunkifyTable(IndirectTable table) { var entries = table.entries.toList(); entries.sort((a, b) => b.length - a.length); var uniqueChunks = []; - var duplicateDetector = - HashMap(equals: _equals, hashCode: _hash); + var duplicateDetector = HashMap( + 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/benchmark/deep_collection_equality.dart b/pkgs/collection/benchmark/deep_collection_equality.dart index 182cf86d1..df4495598 100644 --- a/pkgs/collection/benchmark/deep_collection_equality.dart +++ b/pkgs/collection/benchmark/deep_collection_equality.dart @@ -49,17 +49,13 @@ class DeepCollectionEqualityEqualsBenchmark extends DeepCollectionEqualityBase { 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 bb5843c88..88d1c4f85 100644 --- a/pkgs/collection/lib/src/algorithms.dart +++ b/pkgs/collection/lib/src/algorithms.dart @@ -18,8 +18,11 @@ import 'utils.dart'; /// the objects. In this case, the objects must be [Comparable]. /// /// Returns -1 if [value] is not in the list. -int binarySearch(List sortedList, E value, - {int Function(E, E)? compare}) { +int binarySearch( + List sortedList, + E value, { + int Function(E, E)? compare, +}) { compare ??= defaultCompare; return binarySearchBy(sortedList, identity, compare, value); } @@ -33,9 +36,14 @@ int binarySearch(List sortedList, E value, /// /// If [start] and [end] are supplied, only that range is searched, /// and only that range need to be sorted. -int binarySearchBy(List sortedList, K Function(E element) keyOf, - int Function(K, K) compare, E value, - [int start = 0, int? end]) { +int binarySearchBy( + List 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 @@ int lowerBound(List sortedList, E value, {int Function(E, E)? compare}) { /// /// If [start] and [end] are supplied, only that range is searched, /// and only that range need to be sorted. -int lowerBoundBy(List sortedList, K Function(E element) keyOf, - int Function(K, K) compare, E value, - [int start = 0, int? end]) { +int lowerBoundBy( + List 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 @@ void _reverse(List elements, int start, int end) { /// /// This insertion sort is stable: Equal elements end up in the same order /// as they started in. -void insertionSort(List elements, - {int Function(E, E)? compare, int start = 0, int? end}) { +void insertionSort( + List 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 @@ void insertionSort(List elements, /// /// Performs insertion sort on the [elements] range from [start] to [end]. /// Ordering is the [compare] of the [keyOf] of the elements. -void insertionSortBy(List elements, K Function(E element) keyOf, - int Function(K a, K b) compare, - [int start = 0, int? end]) { +void insertionSortBy( + List 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 @@ const int _mergeSortLimit = 32; /// /// This merge sort is stable: Equal elements end up in the same order /// as they started in. -void mergeSort(List elements, - {int start = 0, int? end, int Function(E, E)? compare}) { +void mergeSort( + List elements, { + int start = 0, + int? end, + int Function(E, E)? compare, +}) { end = RangeError.checkValidRange(start, end, elements.length); compare ??= defaultCompare; @@ -236,9 +261,26 @@ void mergeSort(List elements, _mergeSort(elements, identity, compare, middle, end, scratchSpace, 0); var firstTarget = end - firstLength; _mergeSort( - elements, identity, compare, start, middle, elements, firstTarget); - _merge(identity, compare, elements, firstTarget, end, scratchSpace, 0, - secondLength, elements, start); + elements, + identity, + compare, + start, + middle, + elements, + firstTarget, + ); + _merge( + identity, + compare, + elements, + firstTarget, + end, + scratchSpace, + 0, + secondLength, + elements, + start, + ); } /// Sort [elements] using a merge-sort algorithm. @@ -248,9 +290,13 @@ void mergeSort(List elements, /// If [start] and [end] are provided, only that range is sorted. /// /// Uses insertion sort for smaller sublists. -void mergeSortBy(List elements, K Function(E element) keyOf, - int Function(K a, K b) compare, - [int start = 0, int? end]) { +void mergeSortBy( + List 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 @@ void mergeSortBy(List elements, K Function(E element) keyOf, _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 @@ void mergeSortBy(List elements, K Function(E element) keyOf, /// /// It will work in-place as well. void _movingInsertionSort( - List list, - K Function(E element) keyOf, - int Function(K, K) compare, - int start, - int end, - List target, - int targetOffset) { + List list, + K Function(E element) keyOf, + int Function(K, K) compare, + int start, + int end, + List target, + int targetOffset, +) { var length = end - start; if (length == 0) return; target[targetOffset] = list[start]; @@ -317,17 +374,25 @@ void _movingInsertionSort( /// Allows target to be the same list as [elements], as long as it's not /// overlapping the `start..end` range. void _mergeSort( - List elements, - K Function(E element) keyOf, - int Function(K, K) compare, - int start, - int end, - List target, - int targetOffset) { + List elements, + K Function(E element) keyOf, + int Function(K, K) compare, + int start, + int end, + List target, + int targetOffset, +) { var length = end - start; if (length < _mergeSortLimit) { _movingInsertionSort( - elements, keyOf, compare, start, end, target, targetOffset); + elements, + keyOf, + compare, + start, + end, + target, + targetOffset, + ); return; } var middle = start + (length >> 1); @@ -340,8 +405,18 @@ void _mergeSort( // 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 @@ void _mergeSort( /// This allows the merge to be stable if the first list contains elements /// that started out earlier than the ones in [secondList] void _merge( - K Function(E element) keyOf, - int Function(K, K) compare, - List firstList, - int firstStart, - int firstEnd, - List secondList, - int secondStart, - int secondEnd, - List target, - int targetOffset) { + K Function(E element) keyOf, + int Function(K, K) compare, + List firstList, + int firstStart, + int firstEnd, + List secondList, + int secondStart, + int secondEnd, + List target, + int targetOffset, +) { // No empty lists reaches here. assert(firstStart < firstEnd); assert(secondStart < secondEnd); @@ -387,15 +463,23 @@ void _merge( } // 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 @@ void _merge( /// If [start] and [end] are provided, only that range is sorted. /// /// Uses insertion sort for smaller sublists. -void quickSort(List elements, int Function(E a, E b) compare, - [int start = 0, int? end]) { +void quickSort( + List elements, + int Function(E a, E b) compare, [ + int start = 0, + int? end, +]) { end = RangeError.checkValidRange(start, end, elements.length); _quickSort(elements, identity, compare, Random(), start, end); } @@ -418,14 +506,24 @@ void quickSort(List elements, int Function(E a, E b) compare, /// /// Uses insertion sort for smaller sublists. void quickSortBy( - List list, K Function(E element) keyOf, int Function(K a, K b) compare, - [int start = 0, int? end]) { + List 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(List list, K Function(E element) keyOf, - int Function(K a, K b) compare, Random random, int start, int end) { +void _quickSort( + List 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 6b973e03e..dc6bef929 100644 --- a/pkgs/collection/lib/src/boollist.dart +++ b/pkgs/collection/lib/src/boollist.dart @@ -194,10 +194,7 @@ final class _GrowableBoolList extends BoolList { 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 @@ final class _GrowableBoolList extends BoolList { 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 _GrowableBoolList extends BoolList { final class _NonGrowableBoolList extends BoolList with NonGrowableListMixin { _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 { diff --git a/pkgs/collection/lib/src/canonicalized_map.dart b/pkgs/collection/lib/src/canonicalized_map.dart index 3dc6e37cb..753ebe61e 100644 --- a/pkgs/collection/lib/src/canonicalized_map.dart +++ b/pkgs/collection/lib/src/canonicalized_map.dart @@ -25,9 +25,10 @@ class CanonicalizedMap implements Map { /// 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 @@ class CanonicalizedMap implements Map { /// 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 other, C Function(K key) canonicalize, - {bool Function(K key)? isValidKey}) - : _canonicalize = canonicalize, + CanonicalizedMap.from( + Map other, + C Function(K key) canonicalize, { + bool Function(K key)? isValidKey, + }) : _canonicalize = canonicalize, _isValidKeyFn = isValidKey { addAll(other); } @@ -56,15 +59,19 @@ class CanonicalizedMap implements Map { /// methods that take arbitrary objects. It can be used to filter out keys /// that can't be canonicalized. CanonicalizedMap.fromEntries( - Iterable> entries, C Function(K key) canonicalize, - {bool Function(K key)? isValidKey}) - : _canonicalize = canonicalize, + Iterable> entries, + C Function(K key) canonicalize, { + bool Function(K key)? isValidKey, + }) : _canonicalize = canonicalize, _isValidKeyFn = isValidKey { addEntries(entries); } CanonicalizedMap._( - this._canonicalize, this._isValidKeyFn, Map> base) { + this._canonicalize, + this._isValidKeyFn, + Map> base, + ) { _base.addAll(base); } @@ -92,8 +99,11 @@ class CanonicalizedMap implements Map { } @override - void addEntries(Iterable> entries) => _base.addEntries(entries - .map((e) => MapEntry(_canonicalize(e.key), MapEntry(e.key, e.value)))); + void addEntries(Iterable> entries) => _base.addEntries( + entries.map( + (e) => MapEntry(_canonicalize(e.key), MapEntry(e.key, e.value)), + ), + ); @override Map cast() => _base.cast(); @@ -161,14 +171,16 @@ class CanonicalizedMap implements Map { @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 @@ class CanonicalizedMap implements Map { /// Creates a `Map` (with the canonicalized keys). /// See [toMap]. Map toMapOfCanonicalKeys() => Map.fromEntries( - _base.entries.map((e) => MapEntry(e.key, e.value.value))); + _base.entries.map((e) => MapEntry(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 18db6e7ed..baee82e30 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 @@ class CombinedMapView extends UnmodifiableMapBase { /// the future. @override Iterable 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 0e1df23da..88d1987a2 100644 --- a/pkgs/collection/lib/src/equality.dart +++ b/pkgs/collection/lib/src/equality.dart @@ -51,9 +51,10 @@ class EqualityBy implements Equality { final Equality _inner; - EqualityBy(F Function(E) comparisonKey, - [Equality inner = const DefaultEquality()]) - : _comparisonKey = comparisonKey, + EqualityBy( + F Function(E) comparisonKey, [ + Equality inner = const DefaultEquality(), + ]) : _comparisonKey = comparisonKey, _inner = inner; @override @@ -111,9 +112,9 @@ class IdentityEquality implements Equality { /// The [hash] of `null` is `null.hashCode`. class IterableEquality implements Equality> { final Equality _elementEquality; - const IterableEquality( - [Equality elementEquality = const DefaultEquality()]) - : _elementEquality = elementEquality; + const IterableEquality([ + Equality elementEquality = const DefaultEquality(), + ]) : _elementEquality = elementEquality; @override bool equals(Iterable? elements1, Iterable? elements2) { @@ -163,9 +164,9 @@ class IterableEquality implements Equality> { /// The [hash] of `null` is `null.hashCode`. class ListEquality implements Equality> { final Equality _elementEquality; - const ListEquality( - [Equality elementEquality = const DefaultEquality()]) - : _elementEquality = elementEquality; + const ListEquality([ + Equality elementEquality = const DefaultEquality(), + ]) : _elementEquality = elementEquality; @override bool equals(List? list1, List? list2) { @@ -213,9 +214,10 @@ abstract class _UnorderedEquality> if (identical(elements1, elements2)) return true; if (elements1 == null || elements2 == null) return false; var counts = HashMap( - 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 @@ abstract class _UnorderedEquality> /// and the elements of one set can be paired with the elements /// of the other iterable, so that each pair are equal. class UnorderedIterableEquality extends _UnorderedEquality> { - const UnorderedIterableEquality( - [super.elementEquality = const DefaultEquality()]); + const UnorderedIterableEquality([ + super.elementEquality = const DefaultEquality(), + ]); @override bool isValidKey(Object? o) => o is Iterable; @@ -312,10 +315,10 @@ class _MapEntry { class MapEquality implements Equality> { final Equality _keyEquality; final Equality _valueEquality; - const MapEquality( - {Equality keys = const DefaultEquality(), - Equality values = const DefaultEquality()}) - : _keyEquality = keys, + const MapEquality({ + Equality keys = const DefaultEquality(), + Equality values = const DefaultEquality(), + }) : _keyEquality = keys, _valueEquality = values; @override @@ -428,9 +431,9 @@ class DeepCollectionEquality implements Equality { /// 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()]) - : _base = base, + const DeepCollectionEquality.unordered([ + Equality base = const DefaultEquality(), + ]) : _base = base, _unordered = true; @override diff --git a/pkgs/collection/lib/src/equality_map.dart b/pkgs/collection/lib/src/equality_map.dart index 542977f69..bf12143ae 100644 --- a/pkgs/collection/lib/src/equality_map.dart +++ b/pkgs/collection/lib/src/equality_map.dart @@ -11,10 +11,13 @@ import 'wrappers.dart'; class EqualityMap extends DelegatingMap { /// Creates a map with equality based on [equality]. EqualityMap(Equality 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 @@ class EqualityMap extends DelegatingMap { /// If [other] has multiple keys that are equivalent according to [equality], /// the last one reached during iteration takes precedence. EqualityMap.from(Equality equality, Map 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 8edbba5bd..a716e00e2 100644 --- a/pkgs/collection/lib/src/equality_set.dart +++ b/pkgs/collection/lib/src/equality_set.dart @@ -11,10 +11,13 @@ import 'wrappers.dart'; class EqualitySet extends DelegatingSet { /// Creates a set with equality based on [equality]. EqualitySet(Equality 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 @@ class EqualitySet extends DelegatingSet { /// If [other] has multiple values that are equivalent according to /// [equality], the first one reached during iteration takes precedence. EqualitySet.from(Equality equality, Iterable 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 db8657417..24c7713a5 100644 --- a/pkgs/collection/lib/src/functions.dart +++ b/pkgs/collection/lib/src/functions.dart @@ -12,8 +12,11 @@ import 'utils.dart'; /// 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 mapMap(Map map, - {K2 Function(K1, V1)? key, V2 Function(K1, V1)? value}) { +Map mapMap( + Map 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 @@ Map mapMap(Map map, /// 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 mergeMaps(Map map1, Map map2, - {V Function(V, V)? value}) { +Map mergeMaps( + Map map1, + Map map2, { + V Function(V, V)? value, +}) { var result = Map.of(map1); if (value == null) return result..addAll(map2); @@ -45,8 +51,9 @@ Map mergeMaps(Map map1, Map map2, /// /// Returns a map from keys computed by [key] to the last value for which [key] /// returns that key. -Map lastBy(Iterable values, T Function(S) key) => - {for (var element in values) key(element): element}; +Map lastBy(Iterable 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 @@ Map> groupBy(Iterable values, T Function(S) key) { /// are compared using their [Comparable.compareTo]. /// /// Returns `null` if [values] is empty. -S? minBy(Iterable values, T Function(S) orderBy, - {int Function(T, T)? compare}) { +S? minBy( + Iterable values, + T Function(S) orderBy, { + int Function(T, T)? compare, +}) { compare ??= defaultCompare; S? minValue; @@ -93,8 +103,11 @@ S? minBy(Iterable values, T Function(S) orderBy, /// are compared using their [Comparable.compareTo]. /// /// Returns `null` if [values] is empty. -S? maxBy(Iterable values, T Function(S) orderBy, - {int Function(T, T)? compare}) { +S? maxBy( + Iterable 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 10f467608..d9516e679 100644 --- a/pkgs/collection/lib/src/iterable_extensions.dart +++ b/pkgs/collection/lib/src/iterable_extensions.dart @@ -83,7 +83,9 @@ extension IterableExtension on Iterable { /// The elements are ordered by the [compare] [Comparator] of the /// property [keyOf] of the element. List sortedByCompare( - K Function(T element) keyOf, Comparator compare) { + K Function(T element) keyOf, + Comparator compare, + ) { var elements = [...this]; mergeSortBy(elements, keyOf, compare); return elements; @@ -131,7 +133,9 @@ extension IterableExtension on Iterable { /// then checks whether the results are in non-decreasing order /// using the [compare] [Comparator].. bool isSortedByCompare( - K Function(T element) keyOf, Comparator compare) { + K Function(T element) keyOf, + Comparator compare, + ) { var iterator = this.iterator; if (!iterator.moveNext()) return true; var previousKey = keyOf(iterator.current); @@ -202,7 +206,8 @@ extension IterableExtension on Iterable { /// Expands each element and index to a number of elements in a new iterable. Iterable expandIndexed( - Iterable Function(int index, T element) expand) sync* { + Iterable Function(int index, T element) expand, + ) sync* { var index = 0; for (var element in this) { yield* expand(index++, element); @@ -241,7 +246,9 @@ extension IterableExtension on Iterable { /// Returns the result of the last call to [combine], /// or [initialValue] if there are no elements. R foldIndexed( - 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 @@ extension IterableExtension on Iterable { /// (Set? previous, T element) => (previous ?? {})..add(element)); /// ```` Map groupFoldBy( - 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 = {}; for (var element in this) { var key = keyOf(element); @@ -487,7 +496,8 @@ extension IterableExtension on Iterable { /// print(parts); // ([1], [0, 2], [1, 5, 7], [6, 8, 9]) /// ``` Iterable> 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 @@ extension IterableExtension on Iterable { /// print(parts); // ([1, 0], [2, 1], [5, 7, 6], [8, 9]) /// ``` Iterable> splitAfterIndexed( - bool Function(int index, T element) test) sync* { + bool Function(int index, T element) test, + ) sync* { var index = 0; List? chunk; for (var element in this) { @@ -550,7 +561,8 @@ extension IterableExtension on Iterable { /// print(parts); // ([1], [0, 2], [1, 5, 7], [6, 8, 9]) /// ``` Iterable> 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 @@ extension IterableIterableExtension on Iterable> { /// 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 get flattenedToList => [ - for (final elements in this) ...elements, - ]; + List get flattenedToList => [for (final elements in this) ...elements]; /// The unique sequential elements of each iterable in this iterable. /// @@ -909,9 +919,7 @@ extension IterableIterableExtension on Iterable> { /// 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 get flattenedToSet => { - for (final elements in this) ...elements, - }; + Set 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 9671eaf3f..10af167b4 100644 --- a/pkgs/collection/lib/src/iterable_zip.dart +++ b/pkgs/collection/lib/src/iterable_zip.dart @@ -42,8 +42,11 @@ class _IteratorZip implements Iterator> { 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 40fa8af6c..a301a1ec9 100644 --- a/pkgs/collection/lib/src/list_extensions.dart +++ b/pkgs/collection/lib/src/list_extensions.dart @@ -36,10 +36,20 @@ extension ListExtensions on List { /// 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( - 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( - 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 @@ extension ListExtensions on List { /// 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>( - 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( - 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 @@ extension ListExtensions on List { /// If [start] and [end] are supplied, only that range is searched, /// and only that range need to be sorted. int lowerBoundByCompare( - 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 @@ extension ListExtensions on List { /// /// If [start] and [end] are supplied, only that range is searched, /// and only that range need to be sorted. - int lowerBoundBy>(E element, K Function(E) keyOf, - [int start = 0, int? end]) => + int lowerBoundBy>( + E element, + K Function(E) keyOf, [ + int start = 0, + int? end, + ]) => algorithms.lowerBoundBy( - this, keyOf, compareComparable, element, start, end); + this, + keyOf, + compareComparable, + element, + start, + end, + ); /// Takes an action for each element. /// @@ -172,7 +206,8 @@ extension ListExtensions on List { /// Like [Iterable.expand] except that the callback function is supplied with /// both the index and the element. Iterable expandIndexed( - Iterable Function(int index, E element) expand) sync* { + Iterable Function(int index, E element) expand, + ) sync* { for (var index = 0; index < length; index++) { yield* expand(index, this[index]); } @@ -187,16 +222,22 @@ extension ListExtensions on List { /// /// Sorts elements from [start] to [end], defaulting to the entire list. void sortByCompare( - 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 Function(E element) keyOf, - [int start = 0, int? end]) { + void sortBy>( + K Function(E element) keyOf, [ + int start = 0, + int? end, + ]) { quickSortBy(this, keyOf, compareComparable, start, end); } @@ -301,7 +342,11 @@ extension ListComparableExtensions> on List { /// Returns -1 if [element] does not occur in this list. int binarySearch(E element, [int Function(E, E)? compare]) => algorithms.binarySearchBy( - 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 @@ extension ListComparableExtensions> on List { /// sorted. int lowerBound(E element, [int Function(E, E)? compare]) => algorithms.lowerBoundBy( - this, identity, compare ?? compareComparable, element); + this, + identity, + compare ?? compareComparable, + element, + ); /// Sort a range of elements by [compare]. /// @@ -325,7 +374,12 @@ extension ListComparableExtensions> on List { void sortRange(int start, int end, [int Function(E a, E b)? compare]) { RangeError.checkValidRange(start, end, length); algorithms.quickSortBy( - 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 df5b43b4d..3bf1517bf 100644 --- a/pkgs/collection/lib/src/priority_queue.dart +++ b/pkgs/collection/lib/src/priority_queue.dart @@ -47,8 +47,9 @@ abstract class PriorityQueue { /// as the comparison function, or use a more specialized function /// if one is available. factory PriorityQueue.of( - Iterable elements, int Function(E, E) comparison) = - HeapPriorityQueue.of; + Iterable elements, + int Function(E, E) comparison, + ) = HeapPriorityQueue.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 a3eaba136..f92dbd22a 100644 --- a/pkgs/collection/lib/src/queue_list.dart +++ b/pkgs/collection/lib/src/queue_list.dart @@ -163,8 +163,9 @@ class QueueList extends Object with ListMixin implements Queue { 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 4bc1d54b1..b5a03fbc2 100644 --- a/pkgs/collection/test/algorithms_test.dart +++ b/pkgs/collection/test/algorithms_test.dart @@ -50,15 +50,21 @@ void main() { 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 @@ void main() { expect(lowerBound(l2, C(5), compare: compareC), equals(1)); }); - void testSort(String name, - void Function(List elements, [int? start, int? end]) sort) { + void testSort( + String name, + void Function(List 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 @@ void main() { 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 main() { }); void testSortBy( - String name, - void Function(List elements, K Function(T element) keyOf, - int Function(K a, K b) compare, - [int start, int end]) - sort) { + String name, + void Function( + List 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 @@ void main() { // 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 @@ void main() { List copy = list.toList(); var min = size >> 2; var max = size - min; - mergeSort(list, - start: min, end: max, compare: (a, b) => b.compareTo(a)); + mergeSort( + 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 @@ void main() { 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(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(list), returnsNormally); + }, + ); } class C { @@ -409,8 +431,12 @@ int _compareInt(int a, int b) => a - b; /// Check that a list is sorted according to [compare] of [keyOf] of elements. void expectSorted( - List list, K Function(T element) keyOf, int Function(K a, K b) compare, - [int start = 0, int? end]) { + List 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 da7b73649..821012e11 100644 --- a/pkgs/collection/test/boollist_test.dart +++ b/pkgs/collection/test/boollist_test.dart @@ -28,10 +28,7 @@ void main() { }); 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 aadb7346f..1d1b42156 100644 --- a/pkgs/collection/test/canonicalized_map_test.dart +++ b/pkgs/collection/test/canonicalized_map_test.dart @@ -61,8 +61,10 @@ void main() { 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,19 +127,19 @@ void main() { }); test('values returns all values in the map', () { - 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', + '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'}); + var entries = map.entries.toList(); expect(entries[0].key, '01'); expect(entries[0].value, 'value 01'); @@ -162,8 +164,10 @@ void main() { group('CanonicalizedMap builds an informative string representation', () { dynamic map; setUp(() { - map = CanonicalizedMap(int.parse, - isValidKey: RegExp(r'^\d+$').hasMatch); + map = CanonicalizedMap( + int.parse, + isValidKey: RegExp(r'^\d+$').hasMatch, + ); }); test('for an empty map', () { @@ -176,10 +180,16 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { group('CanonicalizedMap.toMapOfCanonicalKeys', () { test('convert to a `Map`', () { - 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 @@ void main() { group('CanonicalizedMap.toMap', () { test('convert to a `Map`', () { - 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 @@ void main() { 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 d5c90bfe9..d1f58b273 100644 --- a/pkgs/collection/test/combined_wrapper/iterable_test.dart +++ b/pkgs/collection/test/combined_wrapper/iterable_test.dart @@ -16,8 +16,14 @@ void main() { }); 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 2705e391a..d392c4301 100644 --- a/pkgs/collection/test/combined_wrapper/list_test.dart +++ b/pkgs/collection/test/combined_wrapper/list_test.dart @@ -15,10 +15,16 @@ void main() { // 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 9b9a1a83b..4c4f017d1 100644 --- a/pkgs/collection/test/combined_wrapper/map_test.dart +++ b/pkgs/collection/test/combined_wrapper/map_test.dart @@ -23,12 +23,16 @@ void main() { // 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 ab4871167..b805bfd65 100644 --- a/pkgs/collection/test/comparators_test.dart +++ b/pkgs/collection/test/comparators_test.dart @@ -54,7 +54,7 @@ void main() { 'ab', 'z', '{', - '~' + '~', ]; List sortedBy(int Function(String, String)? compare) => @@ -67,21 +67,27 @@ void main() { }); 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 @@ void main() { }); 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 1022726b0..76d4ba879 100644 --- a/pkgs/collection/test/equality_set_test.dart +++ b/pkgs/collection/test/equality_set_test.dart @@ -35,8 +35,14 @@ void main() { 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 ce58df649..bf2368bda 100644 --- a/pkgs/collection/test/equality_test.dart +++ b/pkgs/collection/test/equality_test.dart @@ -42,14 +42,18 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { group('EqualityBy should use a derived value for ', () { var firstEquality = EqualityBy, String>((e) => e.first); var firstInsensitiveEquality = EqualityBy, String>( - (e) => e.first, const CaseInsensitiveEquality()); + (e) => e.first, + const CaseInsensitiveEquality(), + ); var firstObjectEquality = EqualityBy, 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 @@ void main() { }); 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 dd9205977..16878a305 100644 --- a/pkgs/collection/test/extensions_test.dart +++ b/pkgs/collection/test/extensions_test.dart @@ -18,12 +18,16 @@ void main() { 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 @@ void main() { 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 @@ void main() { group('.sortedByCompare', () { test('empty', () { expect( - iterable([]).sortedByCompare(unreachable, unreachable), []); + iterable([]).sortedByCompare(unreachable, unreachable), + [], + ); }); test('singleton', () { - expect(iterable([2]).sortedByCompare(unreachable, unreachable), - [2]); + expect(iterable([2]).sortedByCompare(unreachable, unreachable), [ + 2, + ]); }); test('multiple', () { expect( - iterable([30, 2, 100]) - .sortedByCompare(toString, cmpParseInverse), - [100, 30, 2]); + iterable([ + 30, + 2, + 100, + ]).sortedByCompare(toString, cmpParseInverse), + [100, 30, 2], + ); }); }); group('isSorted', () { @@ -121,33 +134,45 @@ void main() { }); group('.isSortedByCompare', () { test('empty', () { - expect(iterable([]).isSortedByCompare(unreachable, unreachable), - true); + expect( + iterable([]).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([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([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, 1, 2, 3]).isSortedByCompare(toString, cmpParse), + false, + ); + expect( + iterable([4, 3, 2, 1]).isSortedByCompare(toString, cmpParse), + false, + ); }); }); group('.forEachIndexed', () { @@ -280,7 +305,7 @@ void main() { test('multiple', () { expect(iterable(['a', 'b']).mapIndexed((i, s) => [i, s]), [ [0, 'a'], - [1, 'b'] + [1, 'b'], ]); }); }); @@ -298,18 +323,29 @@ void main() { } expect( - iterable([1, 3, 5, 7]) - .whereIndexed((i, x) => log(i, x).isEven), - isEmpty); + iterable([ + 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([1, 3, 5, 7]).whereIndexed((i, x) => x.isOdd), - [1, 3, 5, 7]); + expect(iterable([1, 3, 5, 7]).whereIndexed((i, x) => x.isOdd), [ + 1, + 3, + 5, + 7, + ]); }); test('some', () { - expect(iterable([1, 3, 5, 7]).whereIndexed((i, x) => i.isOdd), - [3, 7]); + expect(iterable([1, 3, 5, 7]).whereIndexed((i, x) => i.isOdd), [ + 3, + 7, + ]); }); }); group('.whereNotIndexed', () { @@ -326,19 +362,27 @@ void main() { } expect( - iterable([1, 3, 5, 7]) - .whereNotIndexed((i, x) => log(i, x).isOdd), - isEmpty); + iterable([ + 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([1, 3, 5, 7]).whereNotIndexed((i, x) => x.isEven), - [1, 3, 5, 7]); + iterable([1, 3, 5, 7]).whereNotIndexed((i, x) => x.isEven), + [1, 3, 5, 7], + ); }); test('some', () { - expect(iterable([1, 3, 5, 7]).whereNotIndexed((i, x) => i.isOdd), - [1, 5]); + expect( + iterable([1, 3, 5, 7]).whereNotIndexed((i, x) => i.isOdd), + [1, 5], + ); }); }); group('.expandIndexed', () { @@ -349,29 +393,42 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { }); 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( - (x) => x.isEven, (p, v) => p == null ? '$v' : '$p:$v'), - {true: '2:4', false: '1:3:5'}); + iterable([1, 2, 3, 4, 5]).groupFoldBy( + (x) => x.isEven, + (p, v) => p == null ? '$v' : '$p:$v', + ), + {true: '2:4', false: '1:3:5'}, + ); }); }); group('.groupSetsBy', () { @@ -578,14 +667,14 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { }); test('single', () { expect(iterable([1]).splitBefore(unreachable), [ - [1] + [1], ]); }); test('no split', () { @@ -623,7 +712,7 @@ void main() { } expect(iterable([1, 2, 3]).splitBefore(log), [ - [1, 2, 3] + [1, 2, 3], ]); expect(trace, [2, 3]); }); @@ -631,13 +720,13 @@ void main() { 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 @@ void main() { }); test('single', () { expect(iterable([1]).splitBeforeIndexed(unreachable), [ - [1] + [1], ]); }); test('no split', () { @@ -660,7 +749,7 @@ void main() { } expect(iterable([1, 2, 3]).splitBeforeIndexed(log), [ - [1, 2, 3] + [1, 2, 3], ]); expect(trace, ['1', 2, '2', 3]); }); @@ -668,17 +757,17 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { } expect(iterable([1, 2, 3]).splitAfter(log), [ - [1, 2, 3] + [1, 2, 3], ]); expect(trace, [1, 2, 3]); }); @@ -710,13 +799,13 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { } 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 @@ void main() { 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 @@ void main() { }); test('single', () { expect(iterable([1]).splitBetween(unreachable), [ - [1] + [1], ]); }); test('no split', () { @@ -781,24 +870,24 @@ void main() { } 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 @@ void main() { }); test('single', () { expect(iterable([1]).splitBetweenIndexed(unreachable), [ - [1] + [1], ]); }); test('no split', () { @@ -819,35 +908,43 @@ void main() { } 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 @@ void main() { group('.whereNotNull', () { test('empty', () { expect( - iterable([]) - .whereNotNull(), // ignore: deprecated_member_use_from_same_package - isEmpty); + iterable( + [], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + isEmpty, + ); }); test('single', () { expect( - iterable([ - null - ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package - isEmpty); + iterable( + [null], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + isEmpty, + ); expect( - iterable([ - 1 - ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package - [1]); + iterable( + [1], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + [1], + ); }); test('multiple', () { expect( - iterable([ - 1, - 3, - 5 - ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package - [1, 3, 5]); - expect( - iterable([ - null, - null, - null - ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package - isEmpty); - expect( - iterable([ - 1, - null, - 3, - null, - 5 - ]).whereNotNull(), // ignore: deprecated_member_use_from_same_package - [1, 3, 5]); + iterable( + [1, 3, 5], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + [1, 3, 5], + ); + expect( + iterable( + [null, null, null], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + isEmpty, + ); + expect( + iterable( + [1, null, 3, null, 5], + ).whereNotNull(), // ignore: deprecated_member_use_from_same_package + [1, 3, 5], + ); }); }); }); @@ -1049,19 +1145,21 @@ void main() { }); test('single value', () { expect( - iterable([ - iterable([1]) - ]).flattened, - [1]); + iterable([ + iterable([1]), + ]).flattened, + [1], + ); }); test('multiple', () { expect( - iterable([ - iterable([1, 2]), - empty, - iterable([3, 4]) - ]).flattened, - [1, 2, 3, 4]); + iterable([ + iterable([1, 2]), + empty, + iterable([3, 4]), + ]).flattened, + [1, 2, 3, 4], + ); }); }); group('.flattenedToList', () { @@ -1074,19 +1172,21 @@ void main() { }); test('single value', () { expect( - iterable([ - iterable([1]) - ]).flattenedToList, - [1]); + iterable([ + iterable([1]), + ]).flattenedToList, + [1], + ); }); test('multiple', () { expect( - iterable([ - iterable([1, 2]), - empty, - iterable([3, 4]) - ]).flattenedToList, - [1, 2, 3, 4]); + iterable([ + iterable([1, 2]), + empty, + iterable([3, 4]), + ]).flattenedToList, + [1, 2, 3, 4], + ); }); }); group('.flattenedToSet', () { @@ -1099,26 +1199,29 @@ void main() { }); test('single value', () { expect( - iterable([ - iterable([1]) - ]).flattenedToSet, - {1}); + iterable([ + iterable([1]), + ]).flattenedToSet, + {1}, + ); }); test('multiple', () { expect( - iterable([ - iterable([1, 2]), - empty, - iterable([3, 4]) - ]).flattenedToSet, - {1, 2, 3, 4}); + iterable([ + iterable([1, 2]), + empty, + iterable([3, 4]), + ]).flattenedToSet, + {1, 2, 3, 4}, + ); expect( - iterable([ - iterable([1, 2, 3]), - empty, - iterable([2, 3, 4]) - ]).flattenedToSet, - {1, 2, 3, 4}); + iterable([ + iterable([1, 2, 3]), + empty, + iterable([2, 3, 4]), + ]).flattenedToSet, + {1, 2, 3, 4}, + ); }); }); }); @@ -1131,10 +1234,9 @@ void main() { ); }); 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 @@ void main() { ); }); 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 @@ void main() { expect(iterable(['a']).sorted(), ['a']); }); test('multiple', () { - expect(iterable(['5', '2', '4', '3', '1']).sorted(cmpParse), - ['1', '2', '3', '4', '5']); + expect(iterable(['5', '2', '4', '3', '1']).sorted(cmpParse), [ + '1', + '2', + '3', + '4', + '5', + ]); expect( - iterable(['5', '2', '4', '3', '1']).sorted(cmpParseInverse), - ['5', '4', '3', '2', '1']); - expect(iterable(['5', '2', '4', '3', '1']).sorted(), - ['1', '2', '3', '4', '5']); + iterable(['5', '2', '4', '3', '1']).sorted(cmpParseInverse), + ['5', '4', '3', '2', '1'], + ); + expect(iterable(['5', '2', '4', '3', '1']).sorted(), [ + '1', + '2', + '3', + '4', + '5', + ]); // Large enough to trigger quicksort. var i256 = Iterable.generate(256, (i) => i ^ 0x55); var sorted256 = [...i256]..sort(); @@ -1454,14 +1566,18 @@ void main() { 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 @@ void main() { expect(iterable([]).elementAtOrNull(0), isNull); }); test('negative index', () async { - expect(() => iterable([1]).elementAtOrNull(-1), - throwsA(isA())); + expect( + () => iterable([1]).elementAtOrNull(-1), + throwsA(isA()), + ); }); test('index within range', () async { expect(iterable([1]).elementAtOrNull(0), 1); @@ -1486,24 +1604,24 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { test('multiple', () { expect(['a', 'b'].mapIndexed((i, s) => [i, s]), [ [0, 'a'], - [1, 'b'] + [1, 'b'], ]); }); }); @@ -2028,13 +2182,19 @@ void main() { return b; } - expect([1, 3, 5, 7].whereIndexed((i, x) => log(i, x).isEven), - isEmpty); + expect( + [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( - [1, 3, 5, 7].whereIndexed((i, x) => x.isOdd), [1, 3, 5, 7]); + expect([1, 3, 5, 7].whereIndexed((i, x) => x.isOdd), [ + 1, + 3, + 5, + 7, + ]); }); test('some', () { expect([1, 3, 5, 7].whereIndexed((i, x) => i.isOdd), [3, 7]); @@ -2053,13 +2213,19 @@ void main() { return b; } - expect([1, 3, 5, 7].whereNotIndexed((i, x) => log(i, x).isOdd), - isEmpty); + expect( + [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([1, 3, 5, 7].whereNotIndexed((i, x) => x.isEven), - [1, 3, 5, 7]); + expect([1, 3, 5, 7].whereNotIndexed((i, x) => x.isEven), [ + 1, + 3, + 5, + 7, + ]); }); test('some', () { expect([1, 3, 5, 7].whereNotIndexed((i, x) => i.isOdd), [1, 5]); @@ -2073,12 +2239,18 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 f60230332..785a202a8 100644 --- a/pkgs/collection/test/functions_test.dart +++ b/pkgs/collection/test/functions_test.dart @@ -11,10 +11,13 @@ void main() { 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 @@ void main() { test("maps the map's keys", () { expect( - mapMap({'foo': 1, 'bar': 2}, - key: (dynamic key, dynamic value) => key[value]), - equals({'o': 1, 'r': 2})); + mapMap({ + 'foo': 1, + 'bar': 2, + }, key: (dynamic key, dynamic value) => key[value]), + equals({'o': 1, 'r': 2}), + ); }); test("maps the map's values", () { expect( - mapMap({'foo': 1, 'bar': 2}, - value: (dynamic key, dynamic value) => key[value]), - equals({'foo': 'o', 'bar': 'r'})); + mapMap({ + '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 @@ void main() { 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 @@ void main() { 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>([ + minBy, Map>( + [ {'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>([ + maxBy, Map>( + [ {'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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 'baz': ['qux'], 'bang': ['zap'], 'qux': [], - 'zap': [] + 'zap': [], }), equals([ // This is expected to return *a* topological ordering, but this isn't @@ -294,22 +350,23 @@ void main() { {'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 @@ void main() { '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 @@ void main() { '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 @@ void main() { {'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 78f54a2a4..26b89e9c2 100644 --- a/pkgs/collection/test/ignore_ascii_case_test.dart +++ b/pkgs/collection/test/ignore_ascii_case_test.dart @@ -34,8 +34,11 @@ void main() { 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 @@ void main() { 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 3881c6af6..ffd119629 100644 --- a/pkgs/collection/test/iterable_zip_test.dart +++ b/pkgs/collection/test/iterable_zip_test.dart @@ -14,102 +14,110 @@ Iterable iterError(Iterable base, int errorValue) { 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 @@ void main() { 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 @@ void main() { 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 a7aafc4f6..fb4aefe21 100644 --- a/pkgs/collection/test/priority_queue_test.dart +++ b/pkgs/collection/test/priority_queue_test.dart @@ -61,14 +61,27 @@ void testInt(PriorityQueue Function() create) { } void testCustom( - PriorityQueue Function(int Function(C, C)? comparator) create) { + PriorityQueue Function(int Function(C, C)? comparator) create, +) { for (var count in [1, 5, 127, 128]) { - testQueue('Custom:$count/null', () => create(null), - List.generate(count, C.new), C(count)); - testQueue('Custom:$count/compare', () => create(compare), - List.generate(count, C.new), C(count)); - testQueue('Custom:$count/compareNeg', () => create(compareNeg), - List.generate(count, (x) => C(count - x)), const C(0)); + testQueue( + 'Custom:$count/null', + () => create(null), + List.generate(count, C.new), + C(count), + ); + testQueue( + 'Custom:$count/compare', + () => create(compare), + List.generate(count, C.new), + C(count), + ); + testQueue( + 'Custom:$count/compareNeg', + () => create(compareNeg), + List.generate(count, (x) => C(count - x)), + const C(0), + ); } } @@ -85,7 +98,10 @@ void testQueue( } void testQueueBody( - PriorityQueue Function() create, List elements, T notElement) { + PriorityQueue Function() create, + List elements, + T notElement, +) { var q = create(); expect(q.isEmpty, isTrue); expect(q, hasLength(0)); @@ -339,11 +355,15 @@ void testConcurrentModification() { var q = HeapPriorityQueue((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 1550f927e..a2c4d8902 100644 --- a/pkgs/collection/test/queue_list_test.dart +++ b/pkgs/collection/test/queue_list_test.dart @@ -225,33 +225,45 @@ void main() { }); 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 @@ void main() { var patternQueue = QueueList()..addAll(['a', 'b']); var stringQueue = patternQueue.cast(); stringQueue.addAll(['c', 'd']); - expect(stringQueue, const TypeMatcher>(), - reason: 'Expected QueueList, got ${stringQueue.runtimeType}'); + expect( + stringQueue, + const TypeMatcher>(), + reason: 'Expected QueueList, got ${stringQueue.runtimeType}', + ); expect(stringQueue, ['a', 'b', 'c', 'd']); @@ -270,8 +285,11 @@ void main() { test('cast throws on mutation when the type is not valid', () { QueueList stringQueue = QueueList(); var numQueue = stringQueue.cast(); - expect(numQueue, const TypeMatcher>(), - reason: 'Expected QueueList, got ${numQueue.runtimeType}'); + expect( + numQueue, + const TypeMatcher>(), + reason: 'Expected QueueList, got ${numQueue.runtimeType}', + ); expect(() => numQueue.add(1), throwsA(isA())); }); @@ -303,5 +321,6 @@ QueueList withInternalGap() { /// Returns a matcher that expects that a closure throws a /// [ConcurrentModificationError]. -final throwsConcurrentModificationError = - throwsA(const TypeMatcher()); +final throwsConcurrentModificationError = throwsA( + const TypeMatcher(), +); diff --git a/pkgs/collection/test/union_set_test.dart b/pkgs/collection/test/union_set_test.dart index d06faf3da..76e491335 100644 --- a/pkgs/collection/test/union_set_test.dart +++ b/pkgs/collection/test/union_set_test.dart @@ -115,7 +115,7 @@ void main() { var set = UnionSet.from([ {duration1}, - {duration2} + {duration2}, ]); expect(set.lookup(const Duration(seconds: 0)), same(duration1)); @@ -138,7 +138,7 @@ void main() { set = UnionSet.from([ {1, 2}, {5}, - innerSet + innerSet, ]); innerSet.add(4); @@ -182,7 +182,7 @@ void main() { var outerSet = { {1, 2}, {5}, - innerSet + innerSet, }; set = UnionSet(outerSet); diff --git a/pkgs/collection/test/unmodifiable_collection_test.dart b/pkgs/collection/test/unmodifiable_collection_test.dart index 12a9a0a77..9d77fa589 100644 --- a/pkgs/collection/test/unmodifiable_collection_test.dart +++ b/pkgs/collection/test/unmodifiable_collection_test.dart @@ -94,7 +94,9 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { }); 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { }); 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 @@ void testIterable(Iterable original, Iterable wrapped, String name) { 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 @@ void testReadList(List original, List wrapped, String name) { 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 @@ void testNoWriteList(List original, List wrapped, String name) { 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 testWriteList(List original, List wrapped, String name) { } void testNoChangeLengthList( - List original, List wrapped, String name) { + List original, + List wrapped, + String name, +) { var copy = List.of(original); void testThrows(String name, void Function() thunk) { @@ -472,7 +514,9 @@ void testReadSet(Set original, Set wrapped, String name) { 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 65a693f74..d08091e04 100644 --- a/pkgs/collection/test/wrapper_test.dart +++ b/pkgs/collection/test/wrapper_test.dart @@ -76,6 +76,7 @@ class InvocationChecker { 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 @@ void main() { // 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 @@ void main() { (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 @@ void main() { (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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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), throwsStateError); - expect(set.lastWhere((element) => element is int, orElse: () => 'baz'), - equals('baz')); + 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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(), equals(['foo', 'bar'])); }); @@ -563,8 +602,10 @@ void main() { setUp(() { map = {}; - set = - MapValueSet(map, (string) => string.substring(0, 1)); + set = MapValueSet( + map, + (string) => string.substring(0, 1), + ); }); testTwoElementSet(() { @@ -672,11 +713,14 @@ void main() { test('.retainAll respects an unusual notion of equality', () { map = HashMap( - equals: (value1, value2) => - value1.toLowerCase() == value2.toLowerCase(), - hashCode: (value) => value.toLowerCase().hashCode); - set = - MapValueSet(map, (string) => string.substring(0, 1)); + equals: (value1, value2) => + value1.toLowerCase() == value2.toLowerCase(), + hashCode: (value) => value.toLowerCase().hashCode, + ); + set = MapValueSet( + map, + (string) => string.substring(0, 1), + ); map['f'] = 'foo'; map['B'] = 'bar'; diff --git a/pkgs/convert/lib/src/codepage.dart b/pkgs/convert/lib/src/codepage.dart index c298ff5a6..86360e0fc 100644 --- a/pkgs/convert/lib/src/codepage.dart +++ b/pkgs/convert/lib/src/codepage.dart @@ -6,60 +6,88 @@ import 'dart:convert'; 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 @@ CodePageDecoder _createDecoder(String characters) { 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 @@ class _NonBmpCodePageDecoder extends Converter, String> 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 @@ class _BmpCodePageDecoder extends Converter, String> 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 @@ class CodePageEncoder extends Converter> { 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 @@ class CodePageEncoder extends Converter> { } 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 fc0a58aa2..00b483817 100644 --- a/pkgs/convert/lib/src/fixed_datetime_formatter.dart +++ b/pkgs/convert/lib/src/fixed_datetime_formatter.dart @@ -87,10 +87,11 @@ class FixedDateTimeFormatter { 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 @@ class FixedDateTimeFormatter { 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 @@ class FixedDateTimeFormatter { 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 @@ class FixedDateTimeFormatter { 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 @@ class FixedDateTimeFormatter { _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 3696d4d96..8b352f449 100644 --- a/pkgs/convert/lib/src/hex/decoder.dart +++ b/pkgs/convert/lib/src/hex/decoder.dart @@ -93,7 +93,10 @@ class _HexDecoderSink extends StringConversionSinkBase { 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 @@ class _HexDecoderByteSink extends ByteConversionSinkBase { void _close([List? 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 @@ class _HexDecoderByteSink extends ByteConversionSinkBase { /// /// If there's a leftover digit at the end of the decoding, this returns that /// digit. Otherwise it returns `null`. -int? _decode(List codeUnits, int sourceStart, int sourceEnd, - List destination, int destinationStart) { +int? _decode( + List codeUnits, + int sourceStart, + int sourceEnd, + List 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 36d6c226d..54aad1396 100644 --- a/pkgs/convert/lib/src/hex/encoder.dart +++ b/pkgs/convert/lib/src/hex/encoder.dart @@ -79,9 +79,10 @@ String _convert(List bytes, int start, int end) { 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 ef9c8a8d8..1e6057f12 100644 --- a/pkgs/convert/lib/src/percent/decoder.dart +++ b/pkgs/convert/lib/src/percent/decoder.dart @@ -33,7 +33,10 @@ class PercentDecoder extends Converter> { 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 @@ class _PercentDecoderSink extends StringConversionSinkBase { 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 @@ class _PercentDecoderByteSink extends ByteConversionSinkBase { void _close([List? 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 @@ int? _decode(List codeUnits, int start, int end, Uint8Buffer buffer) { } void _checkForInvalidCodeUnit( - int codeUnitOr, List codeUnits, int start, int end) { + int codeUnitOr, + List 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 b087b7a82..99a6791bd 100644 --- a/pkgs/convert/lib/src/percent/encoder.dart +++ b/pkgs/convert/lib/src/percent/encoder.dart @@ -96,9 +96,10 @@ String _convert(List bytes, int start, int end) { 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 cfcc1273d..3a0753cca 100644 --- a/pkgs/convert/lib/src/utils.dart +++ b/pkgs/convert/lib/src/utils.dart @@ -30,8 +30,9 @@ int digitForCodeUnit(List codeUnits, int index) { } 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/test/codepage_test.dart b/pkgs/convert/test/codepage_test.dart index cca75e7b7..28557e883 100644 --- a/pkgs/convert/test/codepage_test.dart +++ b/pkgs/convert/test/codepage_test.dart @@ -25,7 +25,7 @@ void main() { latinGreek, latinHebrew, latinThai, - latinArabic + latinArabic, ]) { group('${cp.name} codepage', () { test('ascii compatible', () { @@ -52,14 +52,17 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 30e7ca914..43fea6e69 100644 --- a/pkgs/convert/test/fixed_datetime_formatter_test.dart +++ b/pkgs/convert/test/fixed_datetime_formatter_test.dart @@ -9,7 +9,8 @@ void main() { var noFractionalSeconds = DateTime.utc(0); var skipWeb = { '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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 abd940f62..0b909755f 100644 --- a/pkgs/convert/test/hex_test.dart +++ b/pkgs/convert/test/hex_test.dart @@ -49,8 +49,9 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { sink.add('0'); expect( - results, - equals([ - [], - [0x00] - ])); + results, + equals([ + [], + [0x00], + ]), + ); sink.add(''); expect( - results, - equals([ - [], - [0x00] - ])); + results, + equals([ + [], + [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 @@ void main() { '`', '\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 4e0f605d0..6787b0529 100644 --- a/pkgs/convert/test/percent_test.dart +++ b/pkgs/convert/test/percent_test.dart @@ -18,8 +18,10 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { sink.add('0'); expect( - results, - equals([ - [], - [0x20] - ])); + results, + equals([ + [], + [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 @@ void main() { 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 @@ void main() { 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/lib/src/hash_sink.dart b/pkgs/crypto/lib/src/hash_sink.dart index cd2382304..fcd8aa90f 100644 --- a/pkgs/crypto/lib/src/hash_sink.dart +++ b/pkgs/crypto/lib/src/hash_sink.dart @@ -58,9 +58,12 @@ abstract class HashSink implements Sink> { /// /// [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 @@ abstract class HashSink implements Sink> { // 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 @@ abstract class HashSink implements Sink> { // 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 @@ abstract class HashSink implements Sink> { _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 @@ abstract class HashSink implements Sink> { 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 df30a3fa1..813932588 100644 --- a/pkgs/crypto/lib/src/md5.dart +++ b/pkgs/crypto/lib/src/md5.dart @@ -50,7 +50,7 @@ const _noise = [ 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 @@ const _shiftAmounts = [ 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 @@ class _MD5Sink extends HashSink { 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 5fc13a049..e085cbab2 100644 --- a/pkgs/crypto/lib/src/sha1.dart +++ b/pkgs/crypto/lib/src/sha1.dart @@ -68,11 +68,12 @@ class _Sha1Sink extends HashSink { _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 36808d3ae..ca0c9551c 100644 --- a/pkgs/crypto/lib/src/sha256.dart +++ b/pkgs/crypto/lib/src/sha256.dart @@ -65,7 +65,7 @@ const List _noise = [ 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 @@ abstract class _Sha32BitSink extends HashSink { _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 @@ abstract class _Sha32BitSink extends HashSink { 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 @@ class _Sha256Sink extends _Sha32BitSink { // of the square roots of the first 8 prime numbers. _Sha256Sink(Sink 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 @@ class _Sha224Sink extends _Sha32BitSink { _Sha224Sink(Sink 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 c2a0f9751..b36f7ed79 100644 --- a/pkgs/crypto/lib/src/sha512_fastsinks.dart +++ b/pkgs/crypto/lib/src/sha512_fastsinks.dart @@ -106,17 +106,18 @@ class Sha384Sink extends _Sha64BitSink { Sha384Sink(Sink 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 @@ class Sha512224Sink extends _Sha64BitSink { Sha512224Sink(Sink 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 @@ class Sha512256Sink extends _Sha64BitSink { Sha512256Sink(Sink 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 2dd64e0bc..97060f241 100644 --- a/pkgs/crypto/lib/src/sha512_slowsinks.dart +++ b/pkgs/crypto/lib/src/sha512_slowsinks.dart @@ -77,7 +77,12 @@ abstract class _Sha64BitSink extends HashSink { // 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 @@ abstract class _Sha64BitSink extends HashSink { } 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 @@ abstract class _Sha64BitSink extends HashSink { ((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 @@ abstract class _Sha64BitSink extends HashSink { // 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 @@ abstract class _Sha64BitSink extends HashSink { _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 @@ class Sha384Sink extends _Sha64BitSink { Sha384Sink(Sink 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 @@ class Sha512224Sink extends _Sha64BitSink { Sha512224Sink(Sink 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 @@ class Sha512256Sink extends _Sha64BitSink { Sha512256Sink(Sink 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/test/hmac_md5_test.dart b/pkgs/crypto/test/hmac_md5_test.dart index 0cbcec0d6..f18f9e129 100644 --- a/pkgs/crypto/test/hmac_md5_test.dart +++ b/pkgs/crypto/test/hmac_md5_test.dart @@ -13,8 +13,12 @@ void main() { 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 c7dafa572..e97cec7f9 100644 --- a/pkgs/crypto/test/hmac_sha1_test.dart +++ b/pkgs/crypto/test/hmac_sha1_test.dart @@ -13,8 +13,12 @@ void main() { 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 7b8cbab31..3ed850852 100644 --- a/pkgs/crypto/test/hmac_sha256_test.dart +++ b/pkgs/crypto/test/hmac_sha256_test.dart @@ -13,8 +13,12 @@ void main() { 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 4f2abfaaa..256bece5a 100644 --- a/pkgs/crypto/test/hmac_sha2_test.dart +++ b/pkgs/crypto/test/hmac_sha2_test.dart @@ -117,13 +117,21 @@ void testCase({ 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 f5bb31d83..0f6a3c8f1 100644 --- a/pkgs/crypto/test/sha1_test.dart +++ b/pkgs/crypto/test/sha1_test.dart @@ -31,11 +31,14 @@ void main() { test('close closes the underlying sink', () { var inner = ChunkedConversionSink.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 @@ void main() { 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 @@ void main() { 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 bd8d23fe9..be6bd43aa 100644 --- a/pkgs/crypto/test/sha256_test.dart +++ b/pkgs/crypto/test/sha256_test.dart @@ -16,15 +16,17 @@ void main() { group('SHA2-256', () { group('with a chunked converter', () { test('add may not be called after close', () { - var sink = - sha256.startChunkedConversion(StreamController().sink); + var sink = sha256.startChunkedConversion( + StreamController().sink, + ); sink.close(); expect(() => sink.add([0]), throwsStateError); }); test('close may be called multiple times', () { - var sink = - sha256.startChunkedConversion(StreamController().sink); + var sink = sha256.startChunkedConversion( + StreamController().sink, + ); sink.close(); sink.close(); sink.close(); @@ -33,15 +35,17 @@ void main() { test('close closes the underlying sink', () { var inner = ChunkedConversionSink.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 @@ void main() { }); 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().sink); + var sink = sha224.startChunkedConversion( + StreamController().sink, + ); sink.close(); expect(() => sink.add([0]), throwsStateError); }); test('close may be called multiple times', () { - var sink = - sha224.startChunkedConversion(StreamController().sink); + var sink = sha224.startChunkedConversion( + StreamController().sink, + ); sink.close(); sink.close(); sink.close(); @@ -74,13 +82,16 @@ void main() { test('close closes the underlying sink', () { var inner = ChunkedConversionSink.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 @@ void main() { }); 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 07ad788cd..5fd183d4b 100644 --- a/pkgs/crypto/test/sha512_test.dart +++ b/pkgs/crypto/test/sha512_test.dart @@ -14,15 +14,17 @@ void main() { group('SHA2-384', () { group('with a chunked converter', () { test('add may not be called after close', () { - var sink = - sha384.startChunkedConversion(StreamController().sink); + var sink = sha384.startChunkedConversion( + StreamController().sink, + ); sink.close(); expect(() => sink.add([0]), throwsStateError); }); test('close may be called multiple times', () { - var sink = - sha384.startChunkedConversion(StreamController().sink); + var sink = sha384.startChunkedConversion( + StreamController().sink, + ); sink.close(); sink.close(); sink.close(); @@ -31,14 +33,16 @@ void main() { test('close closes the underlying sink', () { var inner = ChunkedConversionSink.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 @@ void main() { group('SHA2-512', () { group('with a chunked converter', () { test('add may not be called after close', () { - var sink = - sha512.startChunkedConversion(StreamController().sink); + var sink = sha512.startChunkedConversion( + StreamController().sink, + ); sink.close(); expect(() => sink.add([0]), throwsStateError); }); test('close may be called multiple times', () { - var sink = - sha512.startChunkedConversion(StreamController().sink); + var sink = sha512.startChunkedConversion( + StreamController().sink, + ); sink.close(); sink.close(); sink.close(); @@ -66,13 +72,16 @@ void main() { test('close closes the underlying sink', () { var inner = ChunkedConversionSink.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/lib/src/int64.dart b/pkgs/fixnum/lib/src/int64.dart index cb0e1cc6c..4c043212a 100644 --- a/pkgs/fixnum/lib/src/int64.dart +++ b/pkgs/fixnum/lib/src/int64.dart @@ -801,7 +801,12 @@ class Int64 implements IntX { } 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 @@ class Int64 implements IntX { 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 @@ class Int64 implements IntX { 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 @@ class Int64 implements IntX { // 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 5e6c36add..ba47eddc9 100644 --- a/pkgs/fixnum/test/int32_test.dart +++ b/pkgs/fixnum/test/int32_test.dart @@ -84,8 +84,10 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 e74d8936e..50297cb23 100644 --- a/pkgs/fixnum/test/int64_test.dart +++ b/pkgs/fixnum/test/int64_test.dart @@ -20,10 +20,16 @@ void main() { 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 bytes, int h, int l) { @@ -33,10 +39,16 @@ void main() { 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 @@ void main() { expect( () => op(receiver, 'foo'), throwsA( - isA() - .having((p0) => p0.toString(), 'toString', contains('"foo"')), + isA().having( + (p0) => p0.toString(), + 'toString', + contains('"foo"'), + ), ), ); } @@ -139,27 +154,36 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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)); + 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), + ); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 2d28da3ed..173e86db7 100644 --- a/pkgs/fixnum/test/int_64_vm_test.dart +++ b/pkgs/fixnum/test/int_64_vm_test.dart @@ -11,24 +11,42 @@ import 'package:test/test.dart'; 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/tool/gen_docs.dart b/pkgs/lints/tool/gen_docs.dart index e0818931c..54a99adac 100644 --- a/pkgs/lints/tool/gen_docs.dart +++ b/pkgs/lints/tool/gen_docs.dart @@ -186,11 +186,10 @@ String _createRuleTableRow( 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 388a7f86c..38b1ce80c 100644 --- a/pkgs/lints/tool/validate_lib.dart +++ b/pkgs/lints/tool/validate_lib.dart @@ -9,12 +9,11 @@ import 'package:path/path.dart' as p; void main(List args) { print('Validating that there are no .dart source files in lib/ ...'); - final dartSourceFiles = - Directory('lib') - .listSync(recursive: true) - .whereType() - .where((file) => p.extension(file.path) == '.dart') - .toList(); + final dartSourceFiles = Directory('lib') + .listSync(recursive: true) + .whereType() + .where((file) => p.extension(file.path) == '.dart') + .toList(); if (dartSourceFiles.isEmpty) { print('No Dart files found.'); diff --git a/pkgs/logging/lib/src/level.dart b/pkgs/logging/lib/src/level.dart index 366943357..8453d8e2b 100644 --- a/pkgs/logging/lib/src/level.dart +++ b/pkgs/logging/lib/src/level.dart @@ -63,7 +63,7 @@ class Level implements Comparable { 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 8a0ee6180..38f065a60 100644 --- a/pkgs/logging/lib/src/log_record.dart +++ b/pkgs/logging/lib/src/log_record.dart @@ -36,9 +36,15 @@ class LogRecord { /// 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 d9fa2544f..1e0cd5f7c 100644 --- a/pkgs/logging/lib/src/logger.dart +++ b/pkgs/logging/lib/src/logger.dart @@ -135,12 +135,14 @@ class Logger { 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 @@ class Logger { /// 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 @@ class Logger { } 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 @@ class Logger { Stream _getStream() { if (hierarchicalLoggingEnabled || parent == null) { - return (_controller ??= StreamController.broadcast(sync: true)) + return (_controller ??= StreamController.broadcast( + sync: true, + )) .stream; } else { return root._getStream(); diff --git a/pkgs/logging/test/logging_test.dart b/pkgs/logging/test/logging_test.dart index 6bff3d86e..320e2774a 100644 --- a/pkgs/logging/test/logging_test.dart +++ b/pkgs/logging/test/logging_test.dart @@ -129,9 +129,13 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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/bin/os_detect.dart b/pkgs/os_detect/bin/os_detect.dart index d886a4f2c..7669177a9 100644 --- a/pkgs/os_detect/bin/os_detect.dart +++ b/pkgs/os_detect/bin/os_detect.dart @@ -9,8 +9,10 @@ import 'package:os_detect/os_detect.dart' as os_detect; 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 6f31bfd4d..50585ba51 100644 --- a/pkgs/os_detect/lib/src/os_override.dart +++ b/pkgs/os_detect/lib/src/os_override.dart @@ -93,22 +93,23 @@ final class OperatingSystem { @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 @@ final class OperatingSystem { /// This override affects the `operatingSystem` and `version` /// exported by `package:osid/osid.dart`. R overrideOperatingSystem( - 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 ad84a9a6e..214133d5d 100644 --- a/pkgs/os_detect/lib/src/osid_html.dart +++ b/pkgs/os_detect/lib/src/osid_html.dart @@ -9,5 +9,7 @@ import 'os_override.dart'; 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 56b45eb91..8d0e4a8b2 100644 --- a/pkgs/os_detect/lib/src/osid_io.dart +++ b/pkgs/os_detect/lib/src/osid_io.dart @@ -29,5 +29,6 @@ final RecognizedOS? _osType = Platform.operatingSystem == RecognizedOS.linuxId : 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 2e6798ef3..83c252b45 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_kind.dart'; 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/path/benchmark/benchmark.dart b/pkgs/path/benchmark/benchmark.dart index b6647bb22..6eac92959 100644 --- a/pkgs/path/benchmark/benchmark.dart +++ b/pkgs/path/benchmark/benchmark.dart @@ -22,9 +22,7 @@ final platformPaths = { '/', '/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 40f1ea3cc..c8e22e2ea 100644 --- a/pkgs/path/lib/path.dart +++ b/pkgs/path/lib/path.dart @@ -118,23 +118,40 @@ String get separator => context.separator; /// 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 @@ bool isRootRelative(String path) => context.isRootRelative(path); /// 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 fef8bb64c..562806f0b 100644 --- a/pkgs/path/lib/src/context.dart +++ b/pkgs/path/lib/src/context.dart @@ -37,8 +37,10 @@ class Context { 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 @@ class Context { /// /// 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 @@ class Context { part12, part13, part14, - part15 + part15, ]); // If there's a single absolute path, just return it. This is a lot faster @@ -113,8 +117,24 @@ class Context { 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 @@ class Context { /// /// 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 = [ part1, part2, @@ -308,8 +330,10 @@ class Context { // 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 @@ class Context { } 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 @@ void _validateArgList(String method, List args) { // 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 b8f93feb0..e0e6099f9 100644 --- a/pkgs/path/lib/src/parsed_path.dart +++ b/pkgs/path/lib/src/parsed_path.dart @@ -83,7 +83,12 @@ class ParsedPath { } 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 @@ class ParsedPath { // 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 @@ class ParsedPath { List _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().lastWhere((p) => p != '', orElse: () => null); + final file = parts.cast().lastWhere( + (p) => p != '', + orElse: () => null, + ); if (file == null) return ['', '']; if (file == '..') return ['..', '']; @@ -228,5 +241,10 @@ class ParsedPath { } 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 50f4d7e49..08abc18e2 100644 --- a/pkgs/path/lib/src/path_map.dart +++ b/pkgs/path/lib/src/path_map.dart @@ -27,12 +27,13 @@ class PathMap extends MapView { static Map _create(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 424c8a1e5..52b78e20c 100644 --- a/pkgs/path/lib/src/path_set.dart +++ b/pkgs/path/lib/src/path_set.dart @@ -30,13 +30,14 @@ class PathSet extends IterableBase implements Set { static Set _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 b7542c6d6..14c2d8bd7 100644 --- a/pkgs/path/lib/src/style/windows.dart +++ b/pkgs/path/lib/src/style/windows.dart @@ -119,7 +119,10 @@ class WindowsStyle extends InternalStyle { } 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 @@ class WindowsStyle extends InternalStyle { // 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 e88b0c753..1258376f0 100644 --- a/pkgs/path/test/browser_test.dart +++ b/pkgs/path/test/browser_test.dart @@ -13,8 +13,10 @@ void main() { 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 @@ void main() { 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 de22caf73..e428b89af 100644 --- a/pkgs/path/test/io_test.dart +++ b/pkgs/path/test/io_test.dart @@ -41,26 +41,29 @@ void main() { 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; - - // Call "current" once so that it can be cached. - expect(path.normalize(path.absolute(path.current)), equals(tempPath)); - - 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); + 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)); + + 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, + ); }); test('registers changes to the working directory', () { @@ -68,13 +71,19 @@ void main() { 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 @@ void main() { // 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); - - 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')))); - } 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); + 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.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, + ); } diff --git a/pkgs/path/test/posix_test.dart b/pkgs/path/test/posix_test.dart index 121b4e3c1..4c82b67e3 100644 --- a/pkgs/path/test/posix_test.dart +++ b/pkgs/path/test/posix_test.dart @@ -150,35 +150,117 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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'), + '/root/path/a/b/c/d/e/f/g', + ); 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', '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'), - '/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', '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'), - '/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', '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', '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', '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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 1d2a71679..8143e4810 100644 --- a/pkgs/path/test/url_test.dart +++ b/pkgs/path/test/url_test.dart @@ -9,7 +9,9 @@ import 'utils.dart'; 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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('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'); + 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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')); - 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('/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'), + ); + 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 @@ void main() { 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: '/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')); + 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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'); - 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'); + 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', + ); + 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 @@ void main() { 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 @@ void main() { 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 08d4a524e..27d81c829 100644 --- a/pkgs/path/test/utils.dart +++ b/pkgs/path/test/utils.dart @@ -9,24 +9,46 @@ import 'package:test/test.dart'; final throwsPathException = throwsA(const TypeMatcher()); 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 3808354bd..32026294b 100644 --- a/pkgs/path/test/windows_test.dart +++ b/pkgs/path/test/windows_test.dart @@ -9,8 +9,10 @@ import 'package:test/test.dart'; 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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 @@ void main() { 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 @@ void main() { }); 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 @@ void main() { 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'), + 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', + ); 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', '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'); + 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'); + 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'); + 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'); + 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 @@ void main() { 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'); - 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('///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', + ); + 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 @@ void main() { 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 @@ void main() { 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/lib/src/testing/fake_platform.dart b/pkgs/platform/lib/src/testing/fake_platform.dart index 0c028ca42..ca611d8af 100644 --- a/pkgs/platform/lib/src/testing/fake_platform.dart +++ b/pkgs/platform/lib/src/testing/fake_platform.dart @@ -192,7 +192,8 @@ class FakePlatform extends Platform { T _throwIfNull(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/test/fake_platform_test.dart b/pkgs/platform/test/fake_platform_test.dart index 1aa7cbf6c..424133d3c 100644 --- a/pkgs/platform/test/fake_platform_test.dart +++ b/pkgs/platform/test/fake_platform_test.dart @@ -50,7 +50,9 @@ void main() { 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 @@ void main() { }); 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/lib/src/typed_buffer.dart b/pkgs/typed_data/lib/src/typed_buffer.dart index dcb2c5851..50ccd242d 100644 --- a/pkgs/typed_data/lib/src/typed_buffer.dart +++ b/pkgs/typed_data/lib/src/typed_buffer.dart @@ -203,7 +203,11 @@ abstract class TypedDataBuffer extends ListBase { _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 84ce5297c..2147411f9 100644 --- a/pkgs/typed_data/lib/src/typed_queue.dart +++ b/pkgs/typed_data/lib/src/typed_queue.dart @@ -188,8 +188,12 @@ abstract class _TypedQueue> with ListMixin { // [ |===========| 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 @@ abstract class _TypedQueue> with ListMixin { // [=====| 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 @@ abstract class _TypedQueue> with ListMixin { // 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/test/queue_test.dart b/pkgs/typed_data/test/queue_test.dart index c0b1368dc..d9803c671 100644 --- a/pkgs/typed_data/test/queue_test.dart +++ b/pkgs/typed_data/test/queue_test.dart @@ -95,16 +95,46 @@ void main() { 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 @@ void main() { }); }); - 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 @@ void main() { 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 @@ void main() { }); 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 @@ List oneThrough(int n) => List.generate(n, (i) => i + 1); /// Returns a matcher that expects that a closure throws a /// [ConcurrentModificationError]. -final throwsConcurrentModificationError = - throwsA(const TypeMatcher()); +final throwsConcurrentModificationError = throwsA( + const TypeMatcher(), +); diff --git a/pkgs/typed_data/test/typed_buffers_test.dart b/pkgs/typed_data/test/typed_buffers_test.dart index 9d73040ff..937407b17 100644 --- a/pkgs/typed_data/test/typed_buffers_test.dart +++ b/pkgs/typed_data/test/typed_buffers_test.dart @@ -38,7 +38,7 @@ const List browserSafeIntSamples = [ 0x55, 0x02, 0x01, - 0x00 + 0x00, ]; void main() { @@ -57,12 +57,20 @@ void initTests(List intSamples) { 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 @@ const doubleSamples = [ 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 @@ const floatSamples = [ 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 @@ double roundToFloat(double value) { void testFloat32x4Buffer(List floatSamples) { var float4Samples = []; 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 62afcef70..8569191c8 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 @@ void main() { 0x7fffffffffffffff, 0x5555555555555555, ]; - initTests([ - ...browserSafeIntSamples, - ...browserUnsafe, - ]); + initTests([...browserSafeIntSamples, ...browserUnsafe]); } From e990c345f6b1a3b8f39b22812d922abbef79ae43 Mon Sep 17 00:00:00 2001 From: Moritz Date: Thu, 24 Apr 2025 08:21:25 +0200 Subject: [PATCH 3/4] Add changelogs --- pkgs/characters/CHANGELOG.md | 4 ++++ pkgs/characters/pubspec.yaml | 2 +- pkgs/collection/CHANGELOG.md | 1 + pkgs/convert/CHANGELOG.md | 4 ++++ pkgs/convert/pubspec.yaml | 2 +- pkgs/crypto/CHANGELOG.md | 4 ++++ pkgs/crypto/pubspec.yaml | 2 +- pkgs/fixnum/CHANGELOG.md | 1 + pkgs/lints/CHANGELOG.md | 4 ++++ pkgs/lints/pubspec.yaml | 2 +- pkgs/logging/CHANGELOG.md | 4 ++++ pkgs/logging/pubspec.yaml | 2 +- pkgs/os_detect/CHANGELOG.md | 4 ++++ pkgs/os_detect/pubspec.yaml | 2 +- pkgs/path/CHANGELOG.md | 1 + pkgs/platform/CHANGELOG.md | 4 ++++ pkgs/platform/pubspec.yaml | 2 +- pkgs/typed_data/CHANGELOG.md | 4 ++++ pkgs/typed_data/pubspec.yaml | 2 +- 19 files changed, 43 insertions(+), 8 deletions(-) diff --git a/pkgs/characters/CHANGELOG.md b/pkgs/characters/CHANGELOG.md index 29f9c4d6c..7fe7aa9e1 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/pubspec.yaml b/pkgs/characters/pubspec.yaml index a3de2febf..0ab15fbec 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/collection/CHANGELOG.md b/pkgs/collection/CHANGELOG.md index 5164fca3a..e98792930 100644 --- a/pkgs/collection/CHANGELOG.md +++ b/pkgs/collection/CHANGELOG.md @@ -9,6 +9,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/convert/CHANGELOG.md b/pkgs/convert/CHANGELOG.md index 8fc7ff5bf..96d0fe48c 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/pubspec.yaml b/pkgs/convert/pubspec.yaml index 25c46cebe..fa9edcd26 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/crypto/CHANGELOG.md b/pkgs/crypto/CHANGELOG.md index f971b68eb..1b0532018 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/pubspec.yaml b/pkgs/crypto/pubspec.yaml index 9070ce982..b0cd64722 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/fixnum/CHANGELOG.md b/pkgs/fixnum/CHANGELOG.md index 5bec83a6a..8028ca938 100644 --- a/pkgs/fixnum/CHANGELOG.md +++ b/pkgs/fixnum/CHANGELOG.md @@ -3,6 +3,7 @@ * Change `IntX` such that it implements `Comparable`. 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/lints/CHANGELOG.md b/pkgs/lints/CHANGELOG.md index 49b93984a..ff99d8250 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 a6bc6364a..80596661b 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/logging/CHANGELOG.md b/pkgs/logging/CHANGELOG.md index 088183c9c..d781918b3 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/pubspec.yaml b/pkgs/logging/pubspec.yaml index 30b265289..a1c0fca1d 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/os_detect/CHANGELOG.md b/pkgs/os_detect/CHANGELOG.md index e31274102..dc3862f09 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/pubspec.yaml b/pkgs/os_detect/pubspec.yaml index 2e2c0c31f..e669e5b08 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 0216c30e5..6ba956253 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/platform/CHANGELOG.md b/pkgs/platform/CHANGELOG.md index 1e8c4d574..bbc725306 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/pubspec.yaml b/pkgs/platform/pubspec.yaml index 250767240..3f72086ff 100644 --- a/pkgs/platform/pubspec.yaml +++ b/pkgs/platform/pubspec.yaml @@ -2,7 +2,7 @@ name: platform 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/typed_data/CHANGELOG.md b/pkgs/typed_data/CHANGELOG.md index 8763a879e..6f545e2d1 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/pubspec.yaml b/pkgs/typed_data/pubspec.yaml index 6c93be668..678818dba 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 From 2081f6b03a093bd4d1d62404b3aaf13c379c96b0 Mon Sep 17 00:00:00 2001 From: Moritz Date: Thu, 24 Apr 2025 08:25:22 +0200 Subject: [PATCH 4/4] Use dashes, not stars --- pkgs/characters/CHANGELOG.md | 2 +- pkgs/collection/CHANGELOG.md | 1 - pkgs/crypto/CHANGELOG.md | 2 +- pkgs/fixnum/CHANGELOG.md | 4 ++-- pkgs/logging/CHANGELOG.md | 2 +- pkgs/platform/CHANGELOG.md | 2 +- pkgs/typed_data/CHANGELOG.md | 2 +- 7 files changed, 7 insertions(+), 8 deletions(-) diff --git a/pkgs/characters/CHANGELOG.md b/pkgs/characters/CHANGELOG.md index 7fe7aa9e1..199244602 100644 --- a/pkgs/characters/CHANGELOG.md +++ b/pkgs/characters/CHANGELOG.md @@ -1,6 +1,6 @@ ## 1.4.1-wip -* Run `dart format` with the new style. +- Run `dart format` with the new style. ## 1.4.0 diff --git a/pkgs/collection/CHANGELOG.md b/pkgs/collection/CHANGELOG.md index e98792930..743fddf26 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 diff --git a/pkgs/crypto/CHANGELOG.md b/pkgs/crypto/CHANGELOG.md index 1b0532018..4aee58deb 100644 --- a/pkgs/crypto/CHANGELOG.md +++ b/pkgs/crypto/CHANGELOG.md @@ -1,6 +1,6 @@ ## 3.0.7-wip -* Run `dart format` with the new style. +- Run `dart format` with the new style. ## 3.0.6 diff --git a/pkgs/fixnum/CHANGELOG.md b/pkgs/fixnum/CHANGELOG.md index 8028ca938..a505c3e21 100644 --- a/pkgs/fixnum/CHANGELOG.md +++ b/pkgs/fixnum/CHANGELOG.md @@ -1,9 +1,9 @@ ## 1.2.0-wip -* Change `IntX` such that it implements `Comparable`. This makes it +- Change `IntX` such that it implements `Comparable`. 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. +- Run `dart format` with the new style. ## 1.1.1 diff --git a/pkgs/logging/CHANGELOG.md b/pkgs/logging/CHANGELOG.md index d781918b3..d32a8dc37 100644 --- a/pkgs/logging/CHANGELOG.md +++ b/pkgs/logging/CHANGELOG.md @@ -1,6 +1,6 @@ ## 1.3.1-wip -* Run `dart format` with the new style. +- Run `dart format` with the new style. ## 1.3.0 diff --git a/pkgs/platform/CHANGELOG.md b/pkgs/platform/CHANGELOG.md index bbc725306..161b70586 100644 --- a/pkgs/platform/CHANGELOG.md +++ b/pkgs/platform/CHANGELOG.md @@ -1,6 +1,6 @@ ## 3.1.7-wip -* Run `dart format` with the new style. +- Run `dart format` with the new style. ## 3.1.6 diff --git a/pkgs/typed_data/CHANGELOG.md b/pkgs/typed_data/CHANGELOG.md index 6f545e2d1..30858e7f5 100644 --- a/pkgs/typed_data/CHANGELOG.md +++ b/pkgs/typed_data/CHANGELOG.md @@ -1,6 +1,6 @@ ## 1.4.1-wip -* Run `dart format` with the new style. +- Run `dart format` with the new style. ## 1.4.0