readGraphemeAt function

({String grapheme, int nextIndex}) readGraphemeAt(
  1. String s,
  2. int index
)

Reads the grapheme cluster starting at index and returns it along with the next UTF-16 code-unit index.

This is useful when scanning strings with embedded ANSI escape sequences (where we still need index-based parsing for the ASCII control bytes).

Implementation

({String grapheme, int nextIndex}) readGraphemeAt(String s, int index) {
  if (index < 0) index = 0;
  if (index >= s.length) return (grapheme: '', nextIndex: s.length);

  final r = CharacterRange.at(s, index);
  if (!r.moveNext()) return (grapheme: '', nextIndex: s.length);

  final g = r.current;
  final start = r.stringBeforeLength;
  return (grapheme: g, nextIndex: start + g.length);
}