Line data Source code
1 : // Copyright (c) 2013, 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:convert';
7 : import 'dart:typed_data';
8 :
9 : /// A stream of chunks of bytes representing a single piece of data.
10 : class ByteStream extends StreamView<List<int>> {
11 : ByteStream(Stream<List<int>> stream)
12 0 : : super(stream);
13 :
14 : /// Returns a single-subscription byte stream that will emit the given bytes
15 : /// in a single chunk.
16 : factory ByteStream.fromBytes(List<int> bytes) =>
17 0 : new ByteStream(new Stream.fromIterable([bytes]));
18 :
19 : /// Collects the data of this stream in a [Uint8List].
20 : Future<Uint8List> toBytes() {
21 0 : var completer = new Completer<Uint8List>();
22 0 : var sink = new ByteConversionSink.withCallback((bytes) =>
23 0 : completer.complete(new Uint8List.fromList(bytes)));
24 0 : listen(sink.add, onError: completer.completeError, onDone: sink.close,
25 : cancelOnError: true);
26 0 : return completer.future;
27 : }
28 :
29 : /// Collect the data of this stream in a [String], decoded according to
30 : /// [encoding], which defaults to `UTF8`.
31 : Future<String> bytesToString([Encoding encoding=UTF8]) =>
32 0 : encoding.decodeStream(this);
33 :
34 : Stream<String> toStringStream([Encoding encoding=UTF8]) =>
35 0 : encoding.decoder.bind(this);
36 : }
|