readFileInRange function
Public entry point for line-oriented file reading.
Returns lines [offset, offset + maxLines) from a file.
Fast path (regular files < 10 MB): Reads the whole file, then splits lines in memory.
Streaming path (large files): Reads the file in chunks, only accumulating lines in range.
Both paths strip UTF-8 BOM and \r (CRLF -> LF).
Implementation
Future<ReadFileInRangeResult> readFileInRange(
String filePath, {
int offset = 0,
int? maxLines,
int? maxBytes,
bool truncateOnByteLimit = false,
}) async {
final file = File(filePath);
final ioStat = await file.stat();
if (ioStat.type == FileSystemEntityType.directory) {
throw Exception(
"EISDIR: illegal operation on a directory, read '$filePath'",
);
}
final size = ioStat.size;
final mtimeMs = ioStat.modified.millisecondsSinceEpoch.toDouble();
if (ioStat.type == FileSystemEntityType.file && size < _fastPathMaxSize) {
if (!truncateOnByteLimit && maxBytes != null && size > maxBytes) {
throw FileTooLargeError(size, maxBytes);
}
final text = await file.readAsString();
return _readFileInRangeFast(
text,
mtimeMs,
offset,
maxLines,
truncateOnByteLimit ? maxBytes : null,
);
}
return _readFileInRangeStreaming(
filePath,
offset,
maxLines,
maxBytes,
truncateOnByteLimit,
mtimeMs,
);
}