AGENT SKILL

Zig 高性能编程模式

idiomatic-zig

来自 Ghostty 和 TigerBeetle 的地道、高性能 Zig 生产级编程模式。在编写需要快速、安全且易于维护的 Zig 代码时使用。

使用场景Zig 开发
License 许可
MIT
最近更新
2026-11-11
Stars
★ 0
Forks
0

01 前言 Front Matter

name
idiomatic-zig
description
Production patterns for idiomatic, high-performance Zig from Ghostty and TigerBeetle. Use when writing Zig code that needs to be fast, safe, and maintainable.

02 资源文件 15

03 SKILL.md 正文

Idiomatic Zig: Production Patterns from Ghostty & TigerBeetle

Patterns distilled from two flagship Zig projects:

  • Ghostty — GPU-accelerated terminal emulator. SIMD optimization, cache-friendly packed structs, offset-based memory addressing, cross-platform abstraction.
  • TigerBeetle — Distributed financial database. Static allocation discipline, assertion-driven safety, deterministic simulation testing, io_uring integration. Their TIGER_STYLE.md is one of the best coding style guides ever written.

Target version: Zig 0.16. Every example in examples/ compiles and its tests pass on 0.16.0 — run ./check.sh to re-verify. When using the zig-programming skill alongside this one, defer to its version detection for API specifics.

0.16 moved enough ground that a few of these idioms changed shape rather than wording. std.Io is now an interface value passed like an Allocator. The blocking primitives moved out of std.Thread into std.Io. @Type split into @Struct / @Enum / @Int / @Union / @Pointer. And main receives a std.process.Init carrying a ready-made allocator and Io. Where that changes the advice and not just the spelling, it is called out inline below.

How to Use This Skill

Load this skill alongside zig-programming for production Zig work. This skill provides idioms and design philosophy; zig-programming provides syntax, stdlib reference, and version detection.

Writing a new module: Start with Design Philosophy and Naming & Style, then load the relevant reference for your domain.

Optimizing hot paths: Load references/performance-patterns.md.

Reviewing existing code: Check assertion density (2+ per function), naming conventions, struct field order, and error handling patterns.

Reference Files (load as needed)

  • references/memory-patterns.md — Allocator strategies, pools, offset addressing, in-place init (grep: StaticAllocator, BitmapAllocator, Offset, mmap, MemoryPool, errdefer, deinit, init.gpa)
  • references/performance-patterns.md — SIMD, cache lines, branch hints, hot loop extraction (grep: @branchHint, @prefetch, packed struct, fastmem, @divExact, cache_line)
  • references/safety-and-assertions.md — Assertion discipline, NASA Power of Ten, pair assertions (grep: assert, fatal, maybe, comptime unreachable, slow_runtime_safety, verify)
  • references/testing-strategies.md — VOPR, fuzz testing, tripwire error injection, coverage marks (grep: tripwire, VOPR, fuzz, coverage, refAllDecls, verifyIntegrity, swarm, testing.io)
  • references/api-design-patterns.md — Options structs, tagged unions, generic type functions, Io as a dependency (grep: Options, union(enum), TreeType, Renderer, callback, inline else, Io, Cancelable)
  • references/tiger-style-principles.md — Core philosophy from TigerBeetle's style guide (grep: Power of Ten, zero technical debt, 70-line, control plane, data plane)

Example Files

  • examples/assertion_patterns.zig — Comptime assertions, pair assertions, positive/negative space
  • examples/comptime_type_generation.zig — Data table to packed struct + enum + dispatch (@Struct / @Enum)
  • examples/generic_type_function.zig — FooType() pattern with comptime callbacks
  • examples/options_struct.zig — Named arguments via config struct, Io threaded positionally
  • examples/packed_struct.zig — Cache-friendly Cell/Row layout with fast-path skipping
  • examples/static_allocator.zig — Three-phase allocator lifecycle
  • examples/error_handling_patterns.zig — Narrow error sets, translation, errdefer discipline
  • examples/concurrency_patterns.zig — Dirty flags, atomics, blocking queues over std.Io.Mutex

Design Philosophy

Full treatment in references/tiger-style-principles.md.

Safety, performance, developer experience — in that order. When they conflict, this is the priority. Good style advances all three simultaneously.

Simplicity is the hardest revision, not the first attempt. Spend mental energy upfront in design. The "super idea" that solves multiple axes simultaneously is what to look for.

Zero technical debt. Do it right the first time. What ships must be solid — lacking features is acceptable, lacking quality is not.

Be explicit. No hidden control flow, no hidden allocations, no hidden async. Pass options explicitly. Show intent. Minimize dependence on the compiler to do the right thing.

Put a limit on everything. All loops, queues, and buffers must have a fixed upper bound.

Memory Management

Full treatment and code examples in references/memory-patterns.md.

Key patterns:

  • Choose the right allocator per layer — init.gpa at top level, ArenaAllocator for temp work, MemoryPool for fixed-size objects, direct OS allocation for hot paths. In 0.16 do not construct your own top-level allocator: init.gpa is already leak-checking in Debug and smp_allocator/c_allocator in release.
  • Static allocation after init — When memory needs are known at startup, allocate everything upfront, then forbid further allocation. A performance choice, not a universal rule.
  • In-place initialization — Initialize large structs via out pointers to avoid stack copies. Viral — if any field needs it, the container should too.
  • deinit sets undefined — Set self.* = undefined after freeing to catch use-after-free in debug builds.
  • errdefer discipline — Every fallible init must use errdefer to clean up partial state.

Safety & Assertions

Full treatment in references/safety-and-assertions.md.

Key rules:

  • Two assertions per function minimum in production logic. Assertions are a force multiplier for fuzzing. Trivial helpers and wrappers are exempt.
  • Pair assertions — Assert the same property in two different code paths (e.g., before write AND after read).
  • Assert positive AND negative space — assert(index < length) AND assert(value != sentinel).
  • Split compound assertions — assert(a); assert(b); over assert(a and b) for precise diagnostics.
  • Comptime assertions — Assert relationships between constants before execution.
  • Three-tier error strategy — assert (programmer errors), fatal (environmental errors), error unions (operational errors).

Performance

Full treatment with SIMD examples in references/performance-patterns.md.

Key patterns:

  • Think performance at design time — The 1000x wins come from design, not profiling. Back-of-the-envelope across network/disk/memory/CPU.
  • Packed structs for cache-friendly layout — Design hot data to fit in cache lines. Make the zero value meaningful.
  • Row flags for fast-path skipping — Track metadata at the container level to skip expensive per-element work.
  • @branchHint — Mark cold/unlikely/unpredictable branches explicitly.
  • Extract hot loops — Remove self from inner-loop functions so the compiler can freely register-allocate.
  • Show division intent — @divExact, @divFloor, div_ceil instead of generic /.

Error Handling

  • Narrow error sets — Define operation-specific error sets, not anyerror.
  • Error translation at boundaries — Translate subsystem errors to domain-specific names.
  • errdefer comptime unreachable — After a point where no more errors can occur, document it explicitly.

See examples/error_handling_patterns.zig for complete examples.

Comptime Patterns

Detailed examples in references/api-design-patterns.md and examples/comptime_type_generation.zig.

  • Generic data structures via type functions — pub fn FooType(comptime T: type) type { return struct { ... }; }.
  • Type generation from data tables — Define data as a table, generate packed structs and enums at comptime. 0.16 replaced @Type with one builtin per kind: @Struct(layout, backing_int, names, types, attrs), @Enum(Tag, exhaustiveness, names, values), @Int, @Union, @Pointer.
  • inline else for comptime dispatch — Turn runtime enum values into comptime-known values.
  • Platform selection at comptime — pub const Io = switch (builtin.target.os.tag) { ... }.
  • Compile-time layout verification — comptime { assert(@sizeOf(Cell) == 8); }.

Code Organization

  • File-as-struct — Major types get their own TitleCase.zig file; the struct is @This(). Lowercase files are namespace modules.
  • Flat namespacing — Prefer stdx.PRNG over stdx.random.PRNG.
  • Root re-export module — Package root re-exports public types.
  • Config/constants split — Raw config in config.zig, derived constants in constants.zig. Code imports constants, never config directly.
  • Struct field order — Fields first, types next, methods last. Important things near the top.
  • Scoped logging — Every module: const log = std.log.scoped(.module_name);.
  • Modular build system — Keep build.zig thin; delegate to file-structs in src/build/.

Naming & Style

Follow the Zig style guide. Where Ghostty and TigerBeetle disagree, the Zig stdlib is the tiebreaker.

Naming Rules

  • Types: TitleCase — ArrayList, Allocator
  • Functions/methods: camelCase — insertSlice, appendAssumeCapacity
  • Functions returning type: TitleCase — fn ArrayList(comptime T: type) type
  • Variables and constants: snake_case — max_connections, timeout_ms_default
  • File names: TitleCase.zig for file-as-struct, snake_case.zig for namespace modules

Acronyms Are Regular Words

Acronyms follow the same casing rules as any other word, even two-letter ones:

// Correct (stdlib convention):
const XmlParser = struct { ... };
const TcpServer = struct { ... };
const Io = @import("Io.zig");

// Wrong:
const XMLParser = struct { ... };
const IO = @import("IO.zig");

TigerBeetle uses VSRState and Ghostty uses IO — both deviate from the stdlib. Follow the stdlib (Io, Uri, Tcp, Tls).

Name Quality

  • Units/qualifiers last, by descending significance: latency_ms_max, not max_latency_ms.
  • Same-length related names: source_offset / target_offset, not src_offset / dest_offset.
  • No abbreviations — source and target, not src and dest. Exception: primitive loop variables.
  • Nouns over adjectives — replica.pipeline over replica.preparing.
  • Infuse meaning — gpa: Allocator and arena: Allocator over allocator: Allocator.

Formatting

  • Run zig fmt. 4-space indentation. Hard 100-column limit.
  • Braces on if unless it fits on one line.
  • 70-line function limit. Art is born of constraints.
  • Comments are sentences — capital letter, full stop, space after //. Always say why.

API Design

Full examples in references/api-design-patterns.md.

  • Options structs — When arguments can be mixed up (especially multiple integers), use an options struct. Dependencies stay positional, configuration goes in the struct. 0.16's net.IpAddress.listen(address, io, options) is the stdlib's own worked example.
  • Io is a dependency, not ambient authority — Pass std.Io like an Allocator, most-general first (gpa, io, ...). A function with no Io parameter cannot block, touch the disk, or be cancelled — a guarantee the compiler enforces, because every Dir and File operation takes an Io.
  • Tagged unions for state machines — Express multi-state logic as union(enum), not boolean flags.
  • Return struct for multiple values — struct { row: *Row, cell: *Cell }.
  • Callbacks go last — Mirror control flow. Name with calling function as prefix: readSector() / readSectorCallback().
  • Simpler return types — Reduce dimensionality: void > bool > u64 > ?u64 > !u64.

Testing

Full treatment in references/testing-strategies.md.

  • Inline tests — Place tests alongside the code they test, not in separate files.
  • Size assertions — Guard against accidental layout changes with expectEqual(@sizeOf(T), N).
  • Tripwire error injection — Inject errors at specific allocation points to test errdefer cleanup. Zero-cost in production.
  • Deterministic simulation — Stub all non-determinism (clock, network, disk). Seed + commit = reproducible results.
  • Coverage marks — Trace from test to production code, proving the test exercises the intended path.
  • Fuzz every data structure — Dedicated fuzzer per major data structure. Use swarm testing for better coverage.
  • Integrity verification — verifyIntegrity() checks all invariants; assertIntegrity() is a no-op in release.
  • refAllDecls — Make sure all declarations at least compile. It is shallow, so also write _ = &Type.method; for I/O-shaped functions that have no unit test — Zig never analyses a function nothing reaches, which is how untested code silently rots across a release.

Concurrency

  • Default to single-threaded — Design for single-threaded first. Add concurrency only when proven necessary.
  • Run at your own pace — Own the event loop. Batch incoming work, process on your schedule.
  • Dirty flags over locks — Signal what needs updating via packed struct flags rather than locking.
  • Atomic values for cross-thread state — std.atomic.Value(usize).
  • Blocking queues — Fixed-capacity BlockingQueue for producer-consumer between threads.
  • io_uring on Linux — Submit batched I/O operations, process completions in a loop. In 0.16 this is std.Io.Evented, which selects io_uring, kqueue or Dispatch per target.

What Moved in 0.16

The blocking primitives left std.Thread for std.Io, and they take the Io as a parameter:

0.15 0.16
std.Thread.Mutex std.Io.Mutex
std.Thread.RwLock std.Io.RwLock
std.Thread.Condition std.Io.Condition
std.Thread.Semaphore std.Io.Semaphore
std.Thread.ResetEvent std.Io.Event
std.Thread.WaitGroup std.Io.Group (async / await / cancel)

Initialise with the decl literal — mutex: std.Io.Mutex = .init, not = .{}.

Atomics and dirty flags did not move. That is the useful signal: a primitive takes an Io exactly when it can block. If a type needs no Io, it cannot block, and the signature says so without a comment.

Cancellation is the new cost. lock(io) returns Cancelable!void. Propagate that when the wait is genuinely unbounded. Use lockUncancelable(io) when the critical section is O(1) with no I/O inside it, so a bounded wait does not inflate every caller's return type. See examples/concurrency_patterns.zig.

Sources

04 同仓库更多 Skills