bytes property Null safety

  1. @override
Stream<List<int>> bytes
override

The stream of bytes to decode.

This stream is consumed during decoding.

Implementation

@override
Stream<List<int>> get bytes {
  // If content-length is specified, then we can check it for maxSize
  // and just return the original stream.
  if (_hasContentLength) {
    if (_request.headers.contentLength > maxSize) {
      throw Response(
        HttpStatus.requestEntityTooLarge,
        null,
        {"error": "entity length exceeds maximum"},
      );
    }

    return _originalByteStream;
  }

  // If content-length is not specified (e.g., chunked),
  // then we need to check how many bytes we've read to ensure we haven't
  // crossed maxSize
  if (_bufferingController == null) {
    _bufferingController = StreamController<List<int>>(sync: true);

    _originalByteStream.listen(
      (chunk) {
        _bytesRead += chunk.length;
        if (_bytesRead > maxSize) {
          _bufferingController!.addError(
            Response(
              HttpStatus.requestEntityTooLarge,
              null,
              {"error": "entity length exceeds maximum"},
            ),
          );
          _bufferingController!.close();
          return;
        }

        _bufferingController!.add(chunk);
      },
      onDone: () {
        _bufferingController!.close();
      },
      onError: (Object e, StackTrace st) {
        if (!_bufferingController!.isClosed) {
          _bufferingController!.addError(e, st);
          _bufferingController!.close();
        }
      },
      cancelOnError: true,
    );
  }

  return _bufferingController!.stream;
}