Skip to content

Commit a46256a

Browse files
committed
Adjust memory allocation to allocate based on max element wire size
As we add features to the wire format, this makes is simplier to adjust the memory allocation of the wasm For example, the PR can add 24 new bytes of memory to an element operation that defines border properties probably not a big deal, but its nice to keep it in mind
1 parent 28fcefc commit a46256a

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

term-native.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,15 @@ const BoundingBoxStruct = struct<BoundingBox>({
1616

1717
const BOUNDING_BOX = offsets(BoundingBoxStruct);
1818

19+
const WASM_PAGE_BYTES = 65536;
20+
const TEXT_TRANSFER_BUFFER_BYTES = 1024 * 1024;
21+
const CLAY_DEFAULT_MAX_ELEMENT_COUNT = 8192;
22+
23+
// Conservative fixed wire-format budget per element. This covers the largest
24+
// non-text open/close element encoding we currently support; text, element id,
25+
// and snapshot payload bytes live in TEXT_TRANSFER_BUFFER_BYTES.
26+
const MAX_FIXED_ELEMENT_WIRE_BYTES = 116;
27+
1928
export interface Native {
2029
memory: WebAssembly.Memory;
2130
statePtr: number;
@@ -92,10 +101,15 @@ export async function createTermNative(
92101
let heap = ct.__heap_base.value as number;
93102
let size = ct.clayterm_size(w, h);
94103

95-
// grow memory to fit heap + state + ops buffer (1MB headroom for ops)
96-
let needed = heap + size + 1024 * 1024;
97-
let pages = Math.ceil(needed / 65536);
98-
let current = memory.buffer.byteLength / 65536;
104+
// Grow memory once to fit heap + renderer state + fixed transfer buffer.
105+
// The transfer budget is intentionally fixed: text/id/snapshot payload bytes
106+
// get 1MB, and fixed op overhead gets one max-sized element per Clay element.
107+
// Do not grow this dynamically per render; improve the wire format instead.
108+
let transferBytes = TEXT_TRANSFER_BUFFER_BYTES +
109+
CLAY_DEFAULT_MAX_ELEMENT_COUNT * MAX_FIXED_ELEMENT_WIRE_BYTES;
110+
let needed = heap + size + transferBytes;
111+
let pages = Math.ceil(needed / WASM_PAGE_BYTES);
112+
let current = memory.buffer.byteLength / WASM_PAGE_BYTES;
99113
if (pages > current) {
100114
memory.grow(pages - current);
101115
}

0 commit comments

Comments
 (0)