Memory Management & Zero-Churn Design
Terminal UI loops often run 30 to 120 times per second. tui.zig avoids allocator pressure across redraws by keeping persistent buffers bounded and resetting only O(1) arena pointers between frames.
Allocation Lifecycle
tui.init& Resizes: AllocatesApp'sfront/backCellslices (width * height), ANSI staging buffers, and reusable snapshot cache. Resizes grow in place when capacity suffices (Allocatorpassed once totui.init).App.scratch_arena(ui.scratchAllocator()): Stores transient per-frame data (table column rects,Canvas/Chartgrids, dynamic filtered labels). Cleared eachbeginFrame()reusing existing capacity, eliminating repeatedalloc/freecalls after the first frame.- Reusable
app.snapshot(): Serializes the current screen intoApp's capacity-retaining buffer (released inapp.deinit()), avoiding allocate/free churn across tests and inspections. - Inline 32-Byte Cell Storage:
Cellavoids heap indirection for ASCII, box-drawing, Braille, and typical multi-byte emoji clusters. - Owned Widget States &
AppFactories:app.textInput(),app.textArea(),app.treeState(), andapp.commandPalette()reuseapp.allocatorcleanly and release via explicit.deinit(). - Diff-Minimized ANSI Output: Only modified cells emit escapes, skipping redundant CSI cursor moves across contiguous runs and redundant SGR attributes across identical styles.
Per-Frame Scratch & State Ownership Pattern
zig
const State = struct {
tree: tui.TreeState,
input: tui.TextInputState,
screen: tui.VtScreen,
fn deinit(self: *State) void {
self.tree.deinit();
self.input.deinit();
self.screen.deinit();
}
};
fn render(state: *State, ui: *tui.Ui) !void {
// Transient string is valid for this frame and freed on next beginFrame() without heap churn.
const badge = try std.fmt.allocPrint(ui.scratchAllocator(), "Nodes: {d}", .{state.tree.visibleCount(&roots)});
try ui.text(badge, .{}, null);
}