Skip to content

Instantly share code, notes, and snippets.

@TheSantacloud
Created August 16, 2024 17:05
Show Gist options
  • Save TheSantacloud/7ef312e321d426a87faa56c0048cde8c to your computer and use it in GitHub Desktop.
Save TheSantacloud/7ef312e321d426a87faa56c0048cde8c to your computer and use it in GitHub Desktop.
Zig built-ins cheatsheet 0.13.0
@addrSpaceCast(ptr: anytype) anytype Pointer conversion to another address space
@addWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 } Addition with overflow detection
@alignCast(ptr: anytype) anytype Pointer alignment
@alignOf(comptime T: type) comptime_int Alignment for the current target in bytes
@as(comptime T: type, expression) T Safe type coercion
@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: AtomicOrder) T Atomic dereference of pointer
@atomicRmw(comptime T: type, ptr: *T, comptime op: AtomicRmwOp, operand: T, comptime ordering: AtomicOrder) T Atomic modify and return previous value
@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: AtomicOrder) void Atomic store of value at address
@bitCast(value: anytype) anytype Type cast at compile time
@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int Bit offset of field within struct
@bitSizeOf(comptime T: type) comptime_int Type bit size
@breakpoint() void Inserts debug trap, resumes execution possible
@mulAdd(comptime T: type, a: T, b: T, c: T) T Accurate multiply-add operation
@byteSwap(operand: anytype) T Byte order swap
@bitReverse(integer: anytype) T Bitwise reversal of any integer type
@offsetOf(comptime T: type, comptime field_name: []const u8) comptime_int Struct field offset
@call(modifier: std.builtin.CallModifier, function: anytype, args: anytype) anytype Function call with expression evaluation
@cDefine(comptime name: []const u8, value) void Define a macro in a compiler import context
@cImport(expression) type Parse C code into new struct type
@cInclude(comptime path: []const u8) void Appends #include directive to C import buffer
@clz(operand: anytype) anytype Leading zeroes count
@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T Strong atomic compare-exchange operation
@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T Weak atomic compare-and-exchange operation
@compileError(comptime msg: []const u8) noreturn Compile-time check avoidance
@compileLog(args: ...) void Compile-time logging prints arguments as an error
@constCast(value: anytype) DestType Deconst
@ctz(operand: anytype) anytype Count trailing zeroes in integer
@cUndef(comptime name: []const u8) void Undefines macro in cimport context
@cVaArg(operand: *std.builtin.VaList, comptime T: type) T Argument getter
@cVaCopy(src: *std.builtin.VaList) std.builtin.VaList Copy macro implementation
@cVaEnd(src: *std.builtin.VaList) void va_end implementation
@cVaStart() std.builtin.VaList VA Start macro for variadic functions
@divExact(numerator: T, denominator: T) T Exact division guaranteed if denominator != 0
@divFloor(numerator: T, denominator: T) T Floored division
@divTrunc(numerator: T, denominator: T) T Truncated division towards zero
@embedFile(comptime path: []const u8) *const [N:0]u8 Compile time pointer to null-terminated file contents
@enumFromInt(integer: anytype) anytype Enum value from integer conversion
@errorFromInt(value: std.meta.Int(.unsigned, @bitSizeOf(anyerror))) anyerror Integer to Global Error Set conversion
@errorName(err: anyerror) [:0]const u8 Error string representation
@errorReturnTrace() ?*builtin.StackTrace Returns stack trace if error occurs, otherwise null
@errorCast(value: anytype) anytype Error set conversion
@export(declaration, comptime options: std.builtin.ExportOptions) void Create a symbol in the output object file
@extern(T: type, comptime options: std.builtin.ExternOptions) T External symbol reference creator
@fence(order: AtomicOrder) void Introduce happens-before edges between atomic operations
@field(lhs: anytype, comptime field_name: []const u8) (field) Field access via compile-time string
@fieldParentPtr(comptime field_name: []const u8, field_ptr: *T) anytype Struct base pointer
@floatCast(value: anytype) anytype Float type conversion
@floatFromInt(int: anytype) anytype Integer conversion to nearest float representation
@frameAddress() usize Get current stack frame's base pointer
@hasDecl(comptime Container: type, comptime name: []const u8) bool Checks container declaration matching name
@hasField(comptime Container: type, comptime name: []const u8) bool Field exists compile time check
@import(comptime path: []const u8) type Import zig file and add it to build
@inComptime() bool Comptime execution context
@intCast(int: anytype) anytype Integer cast, keeps same numerical value
@intFromBool(value: bool) u1 "Converts bool to u1 integer."
@intFromEnum(enum_or_tagged_union: anytype) anytype Enum to integer conversion
@intFromError(err: anytype) std.meta.Int(.unsigned, @bitSizeOf(anyerror)) Converts error to integer value
@intFromFloat(float: anytype) anytype Integer part to inferred type conversion
@intFromPtr(value: anytype) usize Pointer to integer conversion
@max(a: T, b: T) T Maximum
@memcpy(noalias dest, noalias source) void Memory copy function
@memset(dest, elem) void Securely set all elements to a value
@min(a: T, b: T) T Minimum value or NaN if input is NaN
@wasmMemorySize(index: u32) usize Wasm memory size in pages returned
@wasmMemoryGrow(index: u32, delta: usize) isize Increase Wasm memory size
@mod(numerator: T, denominator: T) T Modulus division
@mulWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 } Product with potential overflow
@panic(message: []const u8) noreturn Invoke panic handler function
@popCount(operand: anytype) anytype Bit Count
@prefetch(ptr: anytype, comptime options: PrefetchOptions) void Prefetch instruction emission
@ptrCast(value: anytype) anytype Pointer casting and conversion
@ptrFromInt(address: usize) anytype Integer to pointer conversion function
@rem(numerator: T, denominator: T) T Remainder division
@returnAddress() usize Return address at end of current function scope
@select(comptime T: type, pred: @Vector(len, bool), a: @Vector(len, T), b: @Vector(len, T)) @Vector(len, T) Element-wise select between two arrays
@setAlignStack(comptime alignment: u29) void Stack align to specified size
@setCold(comptime is_cold: bool) void Function call frequency hint
@setEvalBranchQuota(comptime new_quota: u32) void Increase maximum compile-time branch quota
@setFloatMode(comptime mode: FloatMode) void Float mode settings
@setRuntimeSafety(comptime safety_on: bool) void Enable runtime safety checks
@shlExact(value: T, shift_amt: Log2T) T Left shift operation
@shlWithOverflow(a: anytype, shift_amt: Log2T) struct { @TypeOf(a), u1 } Shift and return result overflow bit
@shrExact(value: T, shift_amt: Log2T) T Right shift operation
@shuffle(comptime E: type, a: @Vector(a_len, E), b: @Vector(b_len, E), comptime mask: @Vector(mask_len, i32)) @Vector(mask_len, E) Vector selection based on mask
@sizeOf(comptime T: type) comptime_int Size of T in bytes
@splat(scalar: anytype) anytype Scalar value repeated in vector
@reduce(comptime op: std.builtin.ReduceOp, value: anytype) E Vector reduction to scalar value
@src() std.builtin.SourceLocation Function name and location struct
@sqrt(value: anytype) @TypeOf(value) Square root
@sin(value: anytype) @TypeOf(value) Floating point sine in radians
@cos(value: anytype) @TypeOf(value) Cosine in radians function
@tan(value: anytype) @TypeOf(value) Tangent function
@exp(value: anytype) @TypeOf(value) Exponential function for floats and float vectors
@exp2(value: anytype) @TypeOf(value) Floating-point base-2 exponential function
@log(value: anytype) @TypeOf(value) Natural logarithm of a float or vector of floats
@log2(value: anytype) @TypeOf(value) Logarithm base 2
@log10(value: anytype) @TypeOf(value) Base-10 logarithm
@abs(value: anytype) anytype Absolute value of integer or float number
@floor(value: anytype) @TypeOf(value) Maximum integer not greater than float
@ceil(value: anytype) @TypeOf(value) Floor of a float or vector of floats
@trunc(value: anytype) @TypeOf(value) Round float to nearest int
@round(value: anytype) @TypeOf(value) Round to nearest integer
@subWithOverflow(a: anytype, b: anytype) struct { @TypeOf(a, b), u1 } Subtract two values, return result and overflow flag
@tagName(value: anytype) [:0]const u8 Enum/Union value to string conversion
@This() type Current struct reference
@trap() noreturn Trap/jam instruction to exit program abnormally
@truncate(integer: anytype) anytype Truncates integer bits to smaller size
@Type(comptime info: std.builtin.Type) type Reify type information into a type
@typeInfo(comptime T: type) std.builtin.Type Type reflection, ordered fields declared
@typeName(T: type) *const [N:0]u8 Fully qualified type name as string
@TypeOf(...) type Determine type of expression(s)
@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union Union initialization via expression
@Vector(len: comptime_int, Element: type) type Vector creation
@volatileCast(value: anytype) DestType Volatile removed from pointer
@workGroupId(comptime dimension: u32) u32 Global Work Group Index
@workGroupSize(comptime dimension: u32) u32 Work group size
@workItemId(comptime dimension: u32) u32 Work item index within work group dimension
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment