Skip to content
This repository has been archived by the owner on Oct 17, 2024. It is now read-only.

Commit

Permalink
Use BytesBuilder for collectBytes (#185)
Browse files Browse the repository at this point in the history
When this utility was first written `BytesBuilder` was only importable
from `dart:io`. Now that it may be imported from the cross platform
`dart:typed_data` it can be used in `package:async`.
  • Loading branch information
natebosch authored Jun 29, 2021
1 parent 27e3a92 commit b8850b3
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 25 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## 2.7.0-dev
## 2.7.1-dev

* Improve performance for `ChunkedStreamReader` by creating fewer internal
sublists and specializing to create views for `Uint8List` chunks.
Expand Down
29 changes: 5 additions & 24 deletions lib/src/byte_collector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,11 @@ CancelableOperation<Uint8List> collectBytesCancelable(
/// so it can cancel the operation.
T _collectBytes<T>(Stream<List<int>> source,
T Function(StreamSubscription<List<int>>, Future<Uint8List>) result) {
var byteLists = <List<int>>[];
var length = 0;
var bytes = BytesBuilder();
var completer = Completer<Uint8List>.sync();
var subscription = source.listen(
(bytes) {
byteLists.add(bytes);
length += bytes.length;
},
onError: completer.completeError,
onDone: () {
completer.complete(_collect(length, byteLists));
},
cancelOnError: true);
var subscription =
source.listen(bytes.add, onError: completer.completeError, onDone: () {
completer.complete(bytes.takeBytes());
}, cancelOnError: true);
return result(subscription, completer.future);
}

// Join a lists of bytes with a known total length into a single [Uint8List].
Uint8List _collect(int length, List<List<int>> byteLists) {
var result = Uint8List(length);
var i = 0;
for (var byteList in byteLists) {
var end = i + byteList.length;
result.setRange(i, end, byteList);
i = end;
}
return result;
}

0 comments on commit b8850b3

Please sign in to comment.