collect method

Future<Uint8List> collect([
  1. Request? request
])

Collects the data from the stream into a single Uint8List

If request is specified, the method will try to read the Content-Length header and pre-allocate memory for a more efficient conversion.

Implementation

Future<Uint8List> collect([Request? request]) async {
  if (request != null) {
    if (request.contentLength case final int contentLength) {
      var offset = 0;
      final bytes = Uint8List(contentLength);
      await for (final block in this) {
        if (offset + block.length > contentLength) {
          bytes.setRange(offset, contentLength, block);
          break;
        } else {
          bytes.setAll(offset, block);
          offset += block.length;
        }
      }

      return bytes;
    }
  }

  return Uint8List.fromList(
    await fold([], (previous, element) => previous..addAll(element)),
  );
}