foldsFindMatchingBracket function

int foldsFindMatchingBracket({
  1. required Rope rope,
  2. required int targetOffset,
  3. int maxScan = 100000,
})

Offset of the bracket matching the one at targetOffset, or -1. Scans in 4 KB slices and gives up after maxScan code units.

Implementation

int foldsFindMatchingBracket({
  required Rope rope,
  required int targetOffset,
  int maxScan = 100000,
}) {
  const open = {0x28: 0x29, 0x5b: 0x5d, 0x7b: 0x7d};
  const close = {0x29: 0x28, 0x5d: 0x5b, 0x7d: 0x7b};
  const chunk = 4096;

  final c = rope.codeUnitAt(targetOffset);
  final forward = open.containsKey(c);
  final match = forward ? open[c] : close[c];
  if (match == null) return -1;

  var depth = 0;
  if (forward) {
    final limit = math.min(rope.length, targetOffset + maxScan);
    for (var base = targetOffset; base < limit; base += chunk) {
      final text = rope.slice(base, math.min(base + chunk, limit));
      for (var i = 0; i < text.length; i++) {
        final u = text.codeUnitAt(i);
        if (u == c) {
          depth++;
        } else if (u == match && --depth == 0) {
          return base + i;
        }
      }
    }
  } else {
    final floor = math.max(0, targetOffset - maxScan);
    for (var end = targetOffset + 1; end > floor; end -= chunk) {
      final start = math.max(floor, end - chunk);
      final text = rope.slice(start, end);
      for (var i = text.length - 1; i >= 0; i--) {
        final u = text.codeUnitAt(i);
        if (u == c) {
          depth++;
        } else if (u == match && --depth == 0) {
          return start + i;
        }
      }
    }
  }
  return -1;
}