// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library byte_stream;

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return fold(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `UTF8`.
  Future<String> bytesToString([Encoding encoding=UTF8]) =>
      toBytes().then((bytes) => encoding.decode(bytes));

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library byte_stream;

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    return fold(new BytesBuilder(), (builder, chunk) => builder..add(chunk))
      .then((builder) => builder.takeBytes());
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `UTF8`.
  Future<String> bytesToString([Encoding encoding=UTF8]) =>
      toBytes().then((bytes) => encoding.decode(bytes));

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

Use BytesBuilder in pkg:http, when accumulating binary data.
Use BytesBuilder in pkg:http, when accumulating binary data.

This should speed up the library significant.

BUG=
R=sgjesse@google.com

Review URL: https://codereview.chromium.org//47923022

git-svn-id: a0fc6a377c96b9059f80895148836233a16d98be@29739 260f80e4-7a28-3924-810f-c04153c831b5
