adjustIndex static method

int adjustIndex(
  1. String s,
  2. int index
)

Adjusts an index to avoid cutting through a grapheme cluster (e.g., emoji surrogate pairs, CJK variation selectors, combining marks). If the index falls inside a multi-code-unit grapheme cluster, moves it back to the start of that cluster.

Implementation

static int adjustIndex(String s, int index) {
  if (index <= 0 || index >= s.length) return index;
  // Fast path: check surrogate pair (most common case)
  final prev = s.codeUnitAt(index - 1);
  final curr = s.codeUnitAt(index);
  if (prev >= 0xD800 && prev <= 0xDBFF && curr >= 0xDC00 && curr <= 0xDFFF) {
    return index - 1;
  }
  // General path: check if index falls inside any grapheme cluster
  return _snapToGraphemeStart(s, index);
}