Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/element-info-allocations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bomb.sh/tty": patch
---

Improves `term.render()` and `result.info.get()` memory use by encoding element ids and text directly into the transfer buffer instead of allocating per string
46 changes: 34 additions & 12 deletions ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,25 +117,48 @@ function sideBg(
function packString(
view: DataView,
bytes: Uint8Array,
str: string,
o: number,
end: number,
context: string,
): number {
let paddedLength = Math.ceil(bytes.length / 4) * 4;
let next = o + 4 + paddedLength;
if (next > end) {
let start = o + 4;
let length = encodeAt(bytes, str, start, end);
if (length < 0 || start + Math.ceil(length / 4) * 4 > end) {
let next = start + Math.ceil(encoder.encode(str).length / 4) * 4;
throw new RangeError(
`transfer buffer capacity exceeded while packing ${context} ` +
`(${next} byte offset, ${end} byte limit). ` +
`Render a smaller visible slice or reduce frame content.`,
);
}

view.setUint32(o, bytes.length, true);
o += 4;
new Uint8Array(view.buffer).set(bytes, o);
o += paddedLength;
return o;
view.setUint32(o, length, true);
return start + Math.ceil(length / 4) * 4;
}

/**
* Encode `str` as UTF-8 into `bytes` at `at`, returning the byte length, or -1
* when it does not fit before `end`. Encoding in place avoids the native
* backing store `encode()` allocates per string, which only a GC frees.
*/
function encodeAt(
bytes: Uint8Array,
str: string,
at: number,
end: number,
): number {
// ASCII, the common case for ids and text, needs no encoder.
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
if (code > 0x7f) {
let rest = encoder.encodeInto(str.slice(i), bytes.subarray(at + i, end));
return rest.read < str.length - i ? -1 : i + rest.written;
}
if (at + i >= end) return -1;
bytes[at + i] = code;
}
return str.length;
}

export function pack(
Expand All @@ -145,6 +168,7 @@ export function pack(
limit?: number,
): number {
let view = new DataView(mem);
let bytes = new Uint8Array(mem);
let end = limit ?? mem.byteLength;
let o = offset;

Expand All @@ -159,8 +183,7 @@ export function pack(
view.setUint32(o, OP_OPEN_ELEMENT, true);
o += 4;

let bytes = encoder.encode(op.id);
o = packString(view, bytes, o, end, "element id");
o = packString(view, bytes, op.id, o, end, "element id");

// §8.5: currentcolor as an element's own color inherits, exactly
// like omitting it, so neither writes a color group.
Expand Down Expand Up @@ -364,8 +387,7 @@ export function pack(
view.setUint32(o, op.caret ?? 0xFFFFFFFF, true);
o += 4;

let str = encoder.encode(op.content);
o = packString(view, str, o, end, "text content");
o = packString(view, bytes, op.content, o, end, "text content");
break;
}
}
Expand Down
19 changes: 13 additions & 6 deletions term-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ export async function createTermNative(
layout(w, h);
setCaps(caps);

let encoder = new TextEncoder();
let transfer = new Uint8Array(memory.buffer, opsBuf, transferBytes);
let view = new DataView(memory.buffer);

return {
memory,
get statePtr() {
Expand Down Expand Up @@ -284,20 +288,23 @@ export async function createTermNative(
getElementInfo(
id: string,
): { bounds: BoundingBox; replay: Op } | undefined {
let enc = new TextEncoder();
let bytes = enc.encode(id);
// Replay lookups run once per unchanged sibling, so reuse the encoder and
// views instead of allocating per call. Growth detaches the old buffer.
if (transfer.buffer !== memory.buffer || transfer.byteOffset !== opsBuf) {
transfer = new Uint8Array(memory.buffer, opsBuf, transferBytes);
view = new DataView(memory.buffer);
}
// Native code consumes the name before writing the result, so the query
// and metadata share storage even when the name fills the workspace.
let out = opsBuf;
if (bytes.length > transferBytes) {
let { read, written } = encoder.encodeInto(id, transfer);
if (read < id.length) {
return undefined;
}
new Uint8Array(memory.buffer).set(bytes, opsBuf);
let found = ct.get_element_info(statePtr!, opsBuf, bytes.length, out);
let found = ct.get_element_info(statePtr!, opsBuf, written, out);
if (!found) {
return undefined;
}
let view = new DataView(memory.buffer);
return {
bounds: {
x: view.getFloat32(out + BOUNDING_BOX.x, true),
Expand Down
21 changes: 21 additions & 0 deletions test/pack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ describe("pack", () => {
);
});

it("packs ids and text as length-prefixed UTF-8", () => {
let encoder = new TextEncoder();
for (
let content of ["ascii", "café", "日本語", "a🙂b", "cafe\u0301", ""]
) {
let memory = new ArrayBuffer(256);
pack([open(content), close()], memory, 0, memory.byteLength);
let view = new DataView(memory);
let expected = encoder.encode(content);
expect(view.getUint32(4, true)).toBe(expected.length);
expect(new Uint8Array(memory, 8, expected.length)).toEqual(expected);
}
});

it("throws a descriptive RangeError when multibyte text exceeds the transfer buffer", () => {
// Fits as UTF-16 code units but not as UTF-8 bytes.
let memory = new ArrayBuffer(32);
expect(() => pack([text("日".repeat(8))], memory, 0, memory.byteLength))
.toThrow(/transfer buffer capacity exceeded while packing text content/);
});

it("throws a descriptive RangeError when an element id exceeds the transfer buffer", () => {
let memory = new ArrayBuffer(16);
let error: unknown;
Expand Down
Loading