szn

Bug 480 — Per-cell SGR bufPrint in the render diff loop

480. Integer-to-string formatting per changed cell

Severity: LOW (performance) Status: ✅ FIXED Files: src/server/render.zig:524-590, src/server/render.zig:45-77

Problem

In renderContent, when a cell’s fg_changed or bg_changed or attr_changed, the code builds SGR sequences with std.fmt.bufPrint into stack buffers — 1 to 14 bufPrint calls per changed cell (1 reset + up to 11 attr codes + fg + bg) (the writeColourFg/writeColourBg helpers at render.zig:45-77 do one per color; the attribute arms add more). Each call runs integer-to-string formatting for color indices / RGB components.

The inputs are finite: Colour is a small tagged enum (default/terminal/16 indexed/RGB). The set of distinct SGR byte sequences is bounded. Formatting the same 3-digit number to ASCII over and over in the inner loop is pure waste.

Proposed Fix

Precompute at startup:

Emission then becomes a mem.copy from a prebuilt table instead of per-cell bufPrint. Same idea applies to the moveTo CUP sequences (render.zig:715-722) — a [(sy × sx)] table of \x1b[{y};{x}H invalidated on resize turns cursor placement into a slice lookup.

Resolution

renderContent (src/server/render.zig) no longer runs std.fmt.bufPrint per changed cell. At comptime it builds a 256-entry fg SGR table (\x1b[38;5;Nm), a 256-entry bg table (\x1b[48;5;Nm), and an 11-entry attribute-fragment table matching Attr’s renderable fields; emission is now an appendFrag memcpy relying on the attrFields.len == attr_sgr.len comptime assert. RGB colours go through a new appendRgbSgr decimal writer (ESC[38/48;2;r;g;bm) with no formatting allocation; it returns 0 on a too-small destination instead of panicking.

Tests: tables checked against bufPrint for representative indices, appendRgbSgr output and overflow guard, and an end-to-end renderContent capture asserting indexed fg, RGB bg and bold sequences.

Verified: zig build test -Doptimize=ReleaseFast — 1012/1012 tests pass.