readSlice method

  1. @override
Future<String?> readSlice(
  1. Uri uri, {
  2. required int maxBytes,
  3. required bool fromEnd,
})
override

At most maxBytes of uri as text, from its end when fromEnd and from its start otherwise — or null when it does not exist.

A cut slice drops the partial line at the cut, so the first (or last) line is whole; a slice with no line break is kept as it is. Bytes that are not UTF-8 are replaced rather than refused: a log is read to be looked at.

Implementation

@override
Future<String?> readSlice(
  Uri uri, {
  required int maxBytes,
  required bool fromEnd,
}) async {
  final file = File(localPathOf(uri));
  if (!file.existsSync()) return null;
  final handle = await file.open();
  try {
    final size = await handle.length();
    final cut = size > maxBytes;
    final start = fromEnd && cut ? size - maxBytes : 0;
    await handle.setPosition(start);
    final bytes = await handle.read(cut ? maxBytes : size);
    final text = utf8.decode(bytes, allowMalformed: true);
    if (!cut) return text;
    return fromEnd ? tomTrimToLineStart(text) : tomTrimToLineEnd(text);
  } finally {
    await handle.close();
  }
}