applyToText method

String applyToText(
  1. String base
)

The text base becomes once this delta is applied.

base is split by rune, the unit the text handlers index by.

Implementation

String applyToText(String base) {
  if (ops.isEmpty) {
    return base;
  }

  // Splice instead of rebuilding the string one character at a time: a delta
  // usually touches a handful of characters.
  final buffer = StringBuffer();
  var offset = 0;

  for (final op in ops) {
    switch (op) {
      case SeqRetain<String>():
        final end = RuneOffsets.skip(base, offset, op.count);
        assert(_reached(offset, end, op.count), _pastTheEnd);
        buffer.write(base.substring(offset, end));
        offset = end;
      case SeqInsert<String>():
        for (final value in op.values) {
          buffer.write(value);
        }
      case SeqDelete<String>():
        final end = RuneOffsets.skip(base, offset, op.count);
        assert(_reached(offset, end, op.count), _pastTheEnd);
        offset = end;
      case SeqMove<String>():
        throw UnsupportedError('a move must be the only op of its delta');
    }
  }

  return (buffer..write(base.substring(offset))).toString();
}