findStopIndex function

int findStopIndex(
  1. List<CaretStop> stops,
  2. String fragmentId,
  3. int offset
)

Implementation

int findStopIndex(List<CaretStop> stops, String fragmentId, int offset) {
  if (!identical(stops, _stopsRefForIndex)) {
    _stopsRefForIndex = stops;
    final m = <String, int>{};
    for (int i = 0; i < stops.length; i++) {
      // A (fragmentId, offset) pair is unique in the rail, so the map is 1:1.
      m['${stops[i].fragmentId}\u0000${stops[i].offset}'] = i;
    }
    _stopExactIndex = m;
  }

  final exact = _stopExactIndex!['$fragmentId\u0000$offset'];
  if (exact != null) return exact;

  // Fallback (rare): nearest offset within the same fragment when the exact
  // caret position is not itself a stop (e.g. stale offset after an edit).
  int bestIdx = -1;
  int bestDist = 1 << 30;
  for (int i = 0; i < stops.length; i++) {
    final s = stops[i];
    if (s.fragmentId == fragmentId) {
      final d = (s.offset - offset).abs();
      if (d < bestDist) {
        bestDist = d;
        bestIdx = i;
      }
    }
  }
  return bestIdx;
}