readBoundedByteStreamSnapshot function

Future<Uint8List> readBoundedByteStreamSnapshot(
  1. Stream<List<int>> source, {
  2. required String resourcePath,
  3. required int maxBytes,
})

Accumulates a bounded byte snapshot from source.

This is public so non-file producers and regression tests can exercise the exact same max+1 overflow behavior without trusting external metadata.

Implementation

Future<Uint8List> readBoundedByteStreamSnapshot(
  Stream<List<int>> source, {
  required String resourcePath,
  required int maxBytes,
}) async {
  if (maxBytes < 0) {
    throw ArgumentError.value(maxBytes, 'maxBytes', 'must not be negative');
  }
  final bytes = BytesBuilder(copy: false);
  await for (final chunk in source) {
    if (chunk.isEmpty) continue;
    final remaining = maxBytes + 1 - bytes.length;
    if (remaining > 0) {
      bytes.add(
        chunk.length <= remaining ? chunk : chunk.sublist(0, remaining),
      );
    }
    if (bytes.length > maxBytes || chunk.length > remaining) {
      throw BoundedFileSnapshotOverflowException(
        path: resourcePath,
        maxBytes: maxBytes,
      );
    }
  }
  return bytes.takeBytes();
}