consolidate_response.dart 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

/// Efficiently converts the response body of an [HttpClientResponse] into a [Uint8List].
10
///
11 12
/// The future returned will forward all errors emitted by [response].
Future<Uint8List> consolidateHttpClientResponseBytes(HttpClientResponse response) {
13 14 15
  // response.contentLength is not trustworthy when GZIP is involved
  // or other cases where an intermediate transformer has been applied
  // to the stream.
16
  final Completer<Uint8List> completer = Completer<Uint8List>.sync();
17 18 19 20 21 22
  final List<List<int>> chunks = <List<int>>[];
  int contentLength = 0;
  response.listen((List<int> chunk) {
    chunks.add(chunk);
    contentLength += chunk.length;
  }, onDone: () {
23
    final Uint8List bytes = Uint8List(contentLength);
24
    int offset = 0;
25
    for (List<int> chunk in chunks) {
26 27
      bytes.setRange(offset, offset + chunk.length, chunk);
      offset += chunk.length;
28 29 30
    }
    completer.complete(bytes);
  }, onError: completer.completeError, cancelOnError: true);
31

32 33
  return completer.future;
}