Terminal emulator: faster write path (ASCII runs, reused lines, no per-char allocation)

- Parser reads the written strings directly (no rune list per write) and
  handles printable ASCII runs and C0 controls straight from the string;
  a run is written into the line in one call (Buffer.writeAscii,
  BufferLine.setAsciiCells), as writeChar would one by one.
- A line leaving a full scrollback (or a one-line region scroll) is
  cleared and reused instead of allocating a 4 KiB line; lines with
  anchors (selection ends) still leave detached. Lines track the cells
  written since made or cleared, so a clear touches only those.
- Grapheme join rejects characters that cannot join before reading the
  cell (it built a String per character); width table covers plane 1.
- Switch dispatch for C0 controls, direct calls for CSI and SGR (torn-off
  handlers are slow in JavaScript); CSI params emptied without clear();
  circular buffer index without %; insert keeps the start index wrapped.
- Terminal.write(notify: false) lets a host notify once per frame.
- tool/perf/terminal_parse_bench.dart: parse throughput in the VM or V8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 02:34:08 +00:00
parent e526150b1e
commit f7ef4d1445
13 changed files with 674 additions and 85 deletions
+55 -44
View File
@@ -1,9 +1,16 @@
import 'dart:collection';
/// The parser's input: the written strings, read one character at a time.
///
/// Positions ([length], [totalConsumed], [rollback]) count UTF-16 code
/// units, so a character outside the BMP counts two. A surrogate pair is
/// read as one code point when both halves are in the same write; a lone
/// surrogate is read as itself, as `String.runes` does. Strings are kept as
/// written rather than decoded into lists, so a write allocates nothing.
class ByteConsumer {
final _queue = ListQueue<List<int>>();
final _queue = ListQueue<String>();
final _consumed = ListQueue<List<int>>();
final _consumed = ListQueue<String>();
var _currentOffset = 0;
@@ -13,37 +20,63 @@ class ByteConsumer {
void add(String data) {
if (data.isEmpty) return;
final runes = data.runes.toList(growable: false);
_queue.addLast(runes);
_length += runes.length;
_queue.addLast(data);
_length += data.length;
}
/// The string being read, with at least one unit left at [offset].
/// Only valid while [isNotEmpty].
String get block {
var data = _queue.first;
while (_currentOffset >= data.length) {
_consumed.add(_queue.removeFirst());
_currentOffset -= data.length;
data = _queue.first;
}
return data;
}
/// Where [block] is read next.
int get offset => _currentOffset;
/// Consumes [units] code units of [block] at once (the caller has read
/// them there).
void skip(int units) {
_currentOffset += units;
_length -= units;
_totalConsumed += units;
}
int peek() {
final data = _queue.first;
if (_currentOffset < data.length) {
return data[_currentOffset];
} else {
final result = consume();
rollback();
return result;
final data = block;
final unit = data.codeUnitAt(_currentOffset);
if (unit & 0xFC00 == 0xD800 && _currentOffset + 1 < data.length) {
final next = data.codeUnitAt(_currentOffset + 1);
if (next & 0xFC00 == 0xDC00) {
return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF);
}
}
return unit;
}
int consume() {
final data = _queue.first;
if (_currentOffset >= data.length) {
_consumed.add(_queue.removeFirst());
_currentOffset -= data.length;
return consume();
final data = block;
final unit = data.codeUnitAt(_currentOffset++);
if (unit & 0xFC00 == 0xD800 && _currentOffset < data.length) {
final next = data.codeUnitAt(_currentOffset);
if (next & 0xFC00 == 0xDC00) {
_currentOffset++;
_length -= 2;
_totalConsumed += 2;
return 0x10000 + ((unit & 0x3FF) << 10) + (next & 0x3FF);
}
}
_length--;
_totalConsumed++;
return data[_currentOffset++];
return unit;
}
/// Rolls back the last [n] call.
/// Rolls back [n] code units.
void rollback([int n = 1]) {
_currentOffset -= n;
_totalConsumed -= n;
@@ -55,7 +88,7 @@ class ByteConsumer {
}
}
/// Rolls back to the state when this consumer had [length] bytes.
/// Rolls back to the state when this consumer had [length] units.
void rollbackTo(int length) {
rollback(length - _length);
}
@@ -83,25 +116,3 @@ class ByteConsumer {
_length = 0;
}
}
// void main() {
// final consumer = ByteConsumer();
// consumer.add(Uint8List.fromList([1, 2, 3]));
// consumer.add(Uint8List.fromList([4, 5, 6]));
// while (consumer.isNotEmpty) {
// print(consumer.consume());
// }
// consumer.rollback(5);
// while (consumer.isNotEmpty) {
// print(consumer.consume());
// }
// consumer.rollbackTo(3);
// while (consumer.isNotEmpty) {
// print(consumer.consume());
// }
// }
+6 -1
View File
@@ -23,7 +23,11 @@ class IndexAwareCircularBuffer<T extends IndexedItem> {
/// the regular index.
@pragma('vm:prefer-inline')
int _getCyclicIndex(int index) {
return (_startIndex + index) % _array.length;
// Indexes run from 0 to the capacity (one past the end when pushing),
// so one subtraction wraps them; `%` is a helper call in JavaScript.
final cyclic = _startIndex + index;
final capacity = _array.length;
return cyclic >= capacity ? cyclic - capacity : cyclic;
}
/// Removes the element at [index] from the list.
@@ -196,6 +200,7 @@ class IndexAwareCircularBuffer<T extends IndexedItem> {
if (_length >= _array.length) {
_startIndex += 1;
if (_startIndex == _array.length) _startIndex = 0;
_absoluteStartIndex += 1;
} else {
_length++;
+6 -1
View File
@@ -36,7 +36,7 @@ class TerminalDebugger with Observable {
final commands = <TerminalCommand>[];
void write(String chunk) {
recorded.addAll(chunk.runes);
recorded.addAll(chunk.codeUnits);
_parser.write(chunk);
notifyListeners();
}
@@ -89,6 +89,11 @@ class _TerminalDebuggerHandler implements EscapeHandler {
onCommand('writeChar(${String.fromCharCode(char)})');
}
@override
void writeAscii(String data, int start, int end) {
onCommand('writeAscii(${data.substring(start, end)})');
}
/* SBC */
@override
+11 -6
View File
@@ -16,7 +16,12 @@ abstract final class UnicodeWidth {
static const _textDefault = 8;
static const _modifierBase = 16;
static final Uint8List _bmp = _buildBmp();
/// The properties of every code point below [_tableEnd]: the BMP and the
/// supplementary plane that holds the emoji. Beyond it, the ranges are
/// searched.
static final Uint8List _table = _buildTable();
static const _tableEnd = 0x20000;
/// Columns [codePoint] takes alone: 0, 1 or 2. Controls are 0.
static int width(int codePoint) {
@@ -55,7 +60,7 @@ abstract final class UnicodeWidth {
codePoint >= 0x1F1E6 && codePoint <= 0x1F1FF;
static int _props(int codePoint) {
if (codePoint < 0x10000) return _bmp[codePoint];
if (codePoint < _tableEnd) return _table[codePoint];
var props = 0;
if (_within(zeroWidthRanges, codePoint)) props |= _zero;
if (_within(wideRanges, codePoint)) props |= _wide;
@@ -65,12 +70,12 @@ abstract final class UnicodeWidth {
return props;
}
static Uint8List _buildBmp() {
final table = Uint8List(0x10000);
static Uint8List _buildTable() {
final table = Uint8List(_tableEnd);
void mark(List<int> ranges, int bit) {
for (var i = 0; i < ranges.length; i += 2) {
if (ranges[i] >= 0x10000) break;
final last = ranges[i + 1] < 0x10000 ? ranges[i + 1] : 0xFFFF;
if (ranges[i] >= _tableEnd) break;
final last = ranges[i + 1] < _tableEnd ? ranges[i + 1] : _tableEnd - 1;
for (var cp = ranges[i]; cp <= last; cp++) {
table[cp] |= bit;
}