readFileRange function
Read up to maxBytes from a file starting at offset.
Returns a flat string from bytes -- no sliced string references to a
larger parent. Returns null if the file is smaller than the offset.
Implementation
Future<ReadFileRangeResult?> readFileRange(
String path,
int offset,
int maxBytes,
) async {
final raf = await File(path).open(mode: FileMode.read);
try {
final size = await raf.length();
if (size <= offset) {
return null;
}
final bytesToRead = min(size - offset, maxBytes);
final buffer = Uint8List(bytesToRead);
await raf.setPosition(offset);
int totalRead = 0;
while (totalRead < bytesToRead) {
final bytesRead = await raf.readInto(buffer, totalRead, bytesToRead);
if (bytesRead == 0) break;
totalRead += bytesRead;
}
return ReadFileRangeResult(
content: String.fromCharCodes(buffer, 0, totalRead),
bytesRead: totalRead,
bytesTotal: size,
);
} finally {
await raf.close();
}
}