readMany method

Future<List<Uint8List>> readMany(
  1. List<int> offsets,
  2. int length
)

Reads many independent ranges concurrently.

Requests are grouped into batches of batchSize so one worker can use a deep I/O queue and one transfer covers many small reads. Exactly adjacent ranges are coalesced into one larger read before batching, which removes most syscalls for sequential/scan workloads. Results are in the same order as offsets; ranges past EOF are zero-filled.

Implementation

Future<List<Uint8List>> readMany(List<int> offsets, int length) async {
  _checkOpen();
  if (length < 0) throw RangeError.value(length, 'length');
  if (offsets.isEmpty) return <Uint8List>[];
  if (length == 0) {
    return List<Uint8List>.generate(offsets.length, (_) => Uint8List(0));
  }

  // Sort by offset, then merge exactly adjacent items into runs.  The
  // original indices are kept so the caller still gets the requested order.
  final entries = <({int offset, int index})>[
    for (var i = 0; i < offsets.length; i++) (offset: offsets[i], index: i),
  ]..sort((a, b) => a.offset.compareTo(b.offset));
  final runs = <_ReadRun>[];
  for (final entry in entries) {
    if (runs.isNotEmpty) {
      final last = runs.last;
      if (entry.offset == last.offset + last.count * length) {
        last.count++;
        last.indices.add(entry.index);
        continue;
      }
    }
    runs.add(_ReadRun(entry.offset, [entry.index]));
  }

  final results = List<Uint8List?>.filled(offsets.length, null);
  final futures = <Future<Object?>>[];
  final groups = <List<_ReadRun>>[];
  for (var start = 0; start < runs.length; start += batchSize) {
    final end = math.min(start + batchSize, runs.length);
    final group = runs.sublist(start, end);
    groups.add(group);
    futures.add(
      _submit('readRanges', {
        'ranges': [
          for (final run in group) [run.offset, run.count * length],
        ],
      }),
    );
  }
  final payloads = await Future.wait(futures);
  for (var g = 0; g < payloads.length; g++) {
    final payload = payloads[g];
    final data = payload is TransferableTypedData
        ? Uint8List.view(payload.materialize())
        : payload as Uint8List;
    var position = 0;
    for (final run in groups[g]) {
      for (var j = 0; j < run.count; j++) {
        final start = position + j * length;
        results[run.indices[j]] = Uint8List.sublistView(
          data,
          start,
          start + length,
        );
      }
      position += run.count * length;
    }
  }
  return results.cast<Uint8List>();
}