readExactly static method

Future<Uint8List> readExactly(
  1. P2PStream stream,
  2. int length
)

Reads exactly length bytes from the stream.

Unlike P2PStream.read, which may return fewer bytes than requested, this method accumulates data until exactly length bytes are read.

Throws StateError if the stream closes before length bytes are read.

Implementation

static Future<Uint8List> readExactly(P2PStream stream, int length) async {
  if (length == 0) {
    return Uint8List(0);
  }

  final buffer = BytesBuilder(copy: false);

  while (buffer.length < length) {
    final remaining = length - buffer.length;
    final chunk = await stream.read(remaining);

    if (chunk.isEmpty) {
      throw StateError(
        'Stream closed after reading ${buffer.length} bytes, '
        'expected $length bytes'
      );
    }

    buffer.add(chunk);
  }

  return buffer.toBytes();
}