OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import "dart:async"; |
| 6 import "dart:typed_data"; |
| 7 |
| 8 /// Collects an asynchronous sequence of byte lists into a single list of bytes. |
| 9 /// |
| 10 /// If the [source] stream emits an error event, |
| 11 /// the collection fails and the returned future completes with the same error. |
| 12 /// |
| 13 /// If any of the input data are not valid bytes, they will be truncated to |
| 14 /// an eight-bit unsigned value in the resulting list. |
| 15 Future<Uint8List> collectBytes(Stream<List<int>> source) { |
| 16 var byteLists = List<List<int>>[]; |
| 17 var length = 0; |
| 18 var completer = new Completer<Uint8List>.sync(); |
| 19 source.listen( |
| 20 (bytes) { |
| 21 byteLists.add(bytes); |
| 22 length += bytes.length; |
| 23 }, |
| 24 onError: completer.completeError, |
| 25 onDone: () { |
| 26 completer.complete(_collect(length, byteLists)); |
| 27 }, |
| 28 cancelOnError: true); |
| 29 return completer.future; |
| 30 } |
| 31 |
| 32 // Join a lists of bytes with a known total length into a single [Uint8List]. |
| 33 Uint8List _collect(int length, List<List<int>> byteLists) { |
| 34 var result = new Uint8List(length); |
| 35 int i = 0; |
| 36 for (var byteList in byteLists) { |
| 37 var end = i + byteList.length; |
| 38 result.setRange(i, end, byteList); |
| 39 i = end; |
| 40 } |
| 41 return result; |
| 42 } |
OLD | NEW |