locateRecord method

Future<int?> locateRecord(
  1. String recordId
)

Streaming id seek (issue #135 AC6): scans the file block-wise for the line whose record id is recordId and returns its byte offset; null when absent. Cost is one pass — callers jump through the sparse offset map instead whenever the record was read before (locatePassCount instruments the difference).

Implementation

Future<int?> locateRecord(String recordId) async {
  final info = await stat();
  if (info == null) return null;
  const block = 1 << 20;
  var offset = 0;
  final needle = '"id":"$recordId"';
  while (offset < info.size) {
    _locatePassCount++;
    final end = (offset + block) < info.size ? offset + block : info.size;
    final bytes = await _readRange(offset, end);
    // Cheap substring gate before any JSON decode.
    if (!_containsAscii(bytes, needle)) {
      offset = end;
      continue;
    }
    final lines = _splitLines(bytes, offset);
    for (final (lineOffset, lineBytes) in lines) {
      final text = utf8.decode(lineBytes, allowMalformed: true);
      if (!text.contains(needle)) continue;
      final SessionRecord record;
      try {
        record = parseSessionEntryLine(text, '', lineOffset);
      } on Object {
        continue; // torn or foreign line: a locate degrades to a miss
      }
      if (record.id == recordId) return lineOffset;
    }
    offset = end;
  }
  return null;
}