getLocation method

CharacterLocation getLocation(
  1. int offset
)

Return the location information for the character at the given offset.

Implementation

CharacterLocation getLocation(int offset) {
  var min = 0;
  var max = lineStarts.length - 1;

  // Subsequent calls to [getLocation] are often for offsets near each other.
  // To take advantage of that, we cache the index of the line start we found
  // when this was last called. If the current offset is on that line or
  // later, we'll skip those early indices completely when searching.
  if (offset >= lineStarts[_previousLine]) {
    min = _previousLine;

    // Before kicking off a full binary search, do a quick check here to see
    // if the new offset is on that exact line.
    if (min == lineStarts.length - 1 || offset < lineStarts[min + 1]) {
      return CharacterLocation(min + 1, offset - lineStarts[min] + 1);
    }
  }

  // Binary search to find the line containing this offset.
  while (min < max) {
    var midpoint = (max - min + 1) ~/ 2 + min;

    if (lineStarts[midpoint] > offset) {
      max = midpoint - 1;
    } else {
      min = midpoint;
    }
  }

  _previousLine = min;

  return CharacterLocation(min + 1, offset - lineStarts[min] + 1);
}