- Builtin Functions
- @addWithOverflow
- @alignCast
- @alignOf
- @ArgType
- @atomicLoad
- @atomicRmw
- @bitCast
- @bitOffsetOf
- @boolToInt
- @breakpoint
- @bswap
- @bitreverse
- @byteOffsetOf
- @bytesToSlice
- @cDefine
- @cImport
- @cInclude
- @clz
- @cmpxchgStrong
- @cmpxchgWeak
- @compileError
- @compileLog
- @ctz
- @cUndef
- @divExact
- @divFloor
- @divTrunc
- @embedFile
- @enumToInt
- @errorName
- @errorReturnTrace
- @errorToInt
- @errSetCast
- @export
- @fence
- @field
- @fieldParentPtr
- @floatCast
- @floatToInt
- @frameAddress
- @handle
- @import
- @inlineCall
- @intCast
- @intToEnum
- @intToError
- @intToFloat
- @intToPtr
- @IntType
- @memberCount
- @memberName
- @memberType
- @memcpy
- @memset
- @mod
- @mulWithOverflow
- @newStackCall
- @noInlineCall
- @OpaqueType
- @panic
- @popCount
- @ptrCast
- @ptrToInt
- @rem
- @returnAddress
- @setAlignStack
- @setCold
- @setEvalBranchQuota
- @setFloatMode
- @setGlobalLinkage
- @setRuntimeSafety
- @shlExact
- @shlWithOverflow
- @shrExact
- @sizeOf
- @sliceToBytes
- @sqrt
- @subWithOverflow
- @tagName
- @TagType
- @This
- @truncate
- @typeId
- @typeInfo
- @typeName
- @typeOf
- @Vector
Builtin Functions
Builtin functions are provided by the compiler and are prefixed with @
. The comptime
keyword on a parameter means that the parameter must be known at compile time.
@addWithOverflow
@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool
Performs result.* = a + b
. If overflow or underflow occurs, stores the overflowed bits in result
and returns true
. If no overflow or underflow occurs, returns false
.
@alignCast
@alignCast(comptime alignment: u29, ptr: var) var
ptr
can be *T
, fn()
, ?*T
, ?fn()
, or []T
. It returns the same type as ptr
except with the alignment adjusted to the new value.
A pointer alignment safety check is added to the generated code to make sure the pointer is aligned as promised.
@alignOf
@alignOf(comptime T: type) comptime_int
This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has this alignment, the alignment can be omitted from the type.
const assert = @import("std").debug.assert;
comptime {
assert(*u32 == *align(@alignOf(u32)) u32);
}
The result is a target-specific compile time constant. It is guaranteed to be less than or equal to @sizeOf(T).
See also:
@ArgType
@ArgType(comptime T: type, comptime n: usize) type
This builtin function takes a function type and returns the type of the parameter at index n
.
T
must be a function type.
Note: This function is deprecated. Use @typeInfo instead.
@atomicLoad
@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T
This builtin function atomically dereferences a pointer and returns the value.
T
must be a pointer type, a bool
, or an integer whose bit count meets these requirements:
- At least 8
- At most the same as usize
- Power of 2
TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe we can remove this restriction
@atomicRmw
@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T
This builtin function atomically modifies memory and then returns the previous value.
T
must be a pointer type, a bool
, or an integer whose bit count meets these requirements:
- At least 8
- At most the same as usize
- Power of 2
TODO right now bool is not accepted. Also I think we could make non powers of 2 work fine, maybe we can remove this restriction
@bitCast
@bitCast(comptime DestType: type, value: var) DestType
Converts a value of one type to another type.
Asserts that @sizeOf(@typeOf(value)) == @sizeOf(DestType)
.
Asserts that @typeId(DestType) != @import("builtin").TypeId.Pointer
. Use @ptrCast
or @intToPtr
if you need this.
Can be used for these things for example:
- Convert
f32
tou32
bits - Convert
i32
tou32
preserving twos complement
Works at compile-time if value
is known at compile time. It's a compile error to bitcast a struct to a scalar type of the same size since structs have undefined layout. However if the struct is packed then it works.
@bitOffsetOf
@bitOffsetOf(comptime T: type, comptime field_name: [] const u8) comptime_int
Returns the bit offset of a field relative to its containing struct.
For non packed structs, this will always be divisible by 8
. For packed structs, non-byte-aligned fields will share a byte offset, but they will have different bit offsets.
See also:
@boolToInt
@boolToInt(value: bool) u1
Converts true
to u1(1)
and false
to u1(0)
.
If the value is known at compile-time, the return type is comptime_int
instead of u1
.
@breakpoint
@breakpoint()
This function inserts a platform-specific debug trap instruction which causes debuggers to break there.
This function is only valid within function scope.
@bswap
@bswap(comptime T: type, value: T) T
T
must be an integer type with bit count evenly divisible by 8.
Swaps the byte order of the integer. This converts a big endian integer to a little endian integer, and converts a little endian integer to a big endian integer.
@bitreverse
@bitreverse(comptime T: type, value: T) T
T
accepts any integer type.
Reverses the bitpattern of an integer value, including the sign bit if applicable.
For example 0b10110110 (u8 = 182
, i8 = -74
) becomes 0b01101101 (u8 = 109
, i8 = 109
).
@byteOffsetOf
@byteOffsetOf(comptime T: type, comptime field_name: [] const u8) comptime_int
Returns the byte offset of a field relative to its containing struct.
See also:
@bytesToSlice
@bytesToSlice(comptime Element: type, bytes: []u8) []Element
Converts a slice of bytes or array of bytes into a slice of Element
. The resulting slice has the same pointer properties as the parameter.
Attempting to convert a number of bytes with a length that does not evenly divide into a slice of elements results in safety-protected Undefined Behavior.
@cDefine
@cDefine(comptime name: []u8, value)
This function can only occur inside @cImport
.
This appends #define $name $value
to the @cImport
temporary buffer.
To define without a value, like this:
#define _GNU_SOURCE
Use the void value, like this:
@cDefine("_GNU_SOURCE", {})
See also:
@cImport
@cImport(expression) type
This function parses C code and imports the functions, types, variables, and compatible macro definitions into a new empty struct type, and then returns that type.
expression
is interpreted at compile time. The builtin functions @cInclude
, @cDefine
, and @cUndef
work within this expression, appending to a temporary buffer which is then parsed as C code.
Usually you should only have one @cImport
in your entire application, because it saves the compiler from invoking clang multiple times, and prevents inline functions from being duplicated.
Reasons for having multiple @cImport
expressions would be:
- To avoid a symbol collision, for example if foo.h and bar.h both
#define CONNECTION_COUNT
- To analyze the C code with different preprocessor defines
See also:
@cInclude
@cInclude(comptime path: []u8)
This function can only occur inside @cImport
.
This appends #include <$path>\n
to the c_import
temporary buffer.
See also:
@clz
@clz(x: T) U
This function counts the number of leading zeroes in x
which is an integer type T
.
The return type U
is an unsigned integer with the minimum number of bits that can represent the value T.bit_count
.
If x
is zero, @clz
returns T.bit_count
.
See also:
@cmpxchgStrong
@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T
This function performs a strong atomic compare exchange operation. It's the equivalent of this code, except atomic:
fn cmpxchgStrongButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
const old_value = ptr.*;
if (old_value == expected_value) {
ptr.* = new_value;
return null;
} else {
return old_value;
}
}
If you are using cmpxchg in a loop, @cmpxchgWeak is the better choice, because it can be implemented more efficiently in machine instructions.
AtomicOrder
can be found with @import("builtin").AtomicOrder
.
@typeOf(ptr).alignment
must be >= @sizeOf(T).
See also:
@cmpxchgWeak
@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T
This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:
fn cmpxchgWeakButNotAtomic(comptime T: type, ptr: *T, expected_value: T, new_value: T) ?T {
const old_value = ptr.*;
if (old_value == expected_value and usuallyTrueButSometimesFalse()) {
ptr.* = new_value;
return null;
} else {
return old_value;
}
}
If you are using cmpxchg in a loop, the sporadic failure will be no problem, and cmpxchgWeak
is the better choice, because it can be implemented more efficiently in machine instructions. However if you need a stronger guarantee, use @cmpxchgStrong.
AtomicOrder
can be found with @import("builtin").AtomicOrder
.
@typeOf(ptr).alignment
must be >= @sizeOf(T).
See also:
@compileError
@compileError(comptime msg: []u8)
This function, when semantically analyzed, causes a compile error with the message msg
.
There are several ways that code avoids being semantically checked, such as using if
or switch
with compile time constants, and comptime
functions.
@compileLog
@compileLog(args: ...)
This function prints the arguments passed to it at compile-time.
To prevent accidentally leaving compile log statements in a codebase, a compilation error is added to the build, pointing to the compile log statement. This error prevents code from being generated, but does not otherwise interfere with analysis.
This function can be used to do "printf debugging" on compile-time executing code.
test.zig
const warn = @import("std").debug.warn;
const num1 = blk: {
var val1: i32 = 99;
@compileLog("comptime val1 = ", val1);
val1 = val1 + 1;
break :blk val1;
};
test "main" {
@compileLog("comptime in main");
warn("Runtime in main, num1 = {}.\n", num1);
}
$ zig test test.zig
| "comptime in main"
| "comptime val1 = ", 99
/home/andy/dev/zig/docgen_tmp/test.zig:11:5: error: found compile log statement
@compileLog("comptime in main");
^
/home/andy/dev/zig/docgen_tmp/test.zig:5:5: error: found compile log statement
@compileLog("comptime val1 = ", val1);
^
will ouput:
If all @compileLog
calls are removed or not encountered by analysis, the program compiles successfully and the generated executable prints:
test.zig
const warn = @import("std").debug.warn;
const num1 = blk: {
var val1: i32 = 99;
val1 = val1 + 1;
break :blk val1;
};
test "main" {
warn("Runtime in main, num1 = {}.\n", num1);
}
$ zig test test.zig
Test 1/1 main...Runtime in main, num1 = 100.
OK
All tests passed.
@ctz
@ctz(x: T) U
This function counts the number of trailing zeroes in x
which is an integer type T
.
The return type U
is an unsigned integer with the minimum number of bits that can represent the value T.bit_count
.
If x
is zero, @ctz
returns T.bit_count
.
See also:
@cUndef
@cUndef(comptime name: []u8)
This function can only occur inside @cImport
.
This appends #undef $name
to the @cImport
temporary buffer.
See also:
@divExact
@divExact(numerator: T, denominator: T) T
Exact division. Caller guarantees denominator != 0
and @divTrunc(numerator, denominator) * denominator == numerator
.
@divExact(6, 3) == 2
@divExact(a, b) * b == a
For a function that returns a possible error code, use @import("std").math.divExact
.
See also:
@divFloor
@divFloor(numerator: T, denominator: T) T
Floored division. Rounds toward negative infinity. For unsigned integers it is the same as numerator / denominator
. Caller guarantees denominator != 0
and !(@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)
.
@divFloor(-5, 3) == -2
@divFloor(a, b) + @mod(a, b) == a
For a function that returns a possible error code, use @import("std").math.divFloor
.
See also:
@divTrunc
@divTrunc(numerator: T, denominator: T) T
Truncated division. Rounds toward zero. For unsigned integers it is the same as numerator / denominator
. Caller guarantees denominator != 0
and !(@typeId(T) == builtin.TypeId.Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1)
.
@divTrunc(-5, 3) == -1
@divTrunc(a, b) + @rem(a, b) == a
For a function that returns a possible error code, use @import("std").math.divTrunc
.
See also:
@embedFile
@embedFile(comptime path: []const u8) [X]u8
This function returns a compile time constant fixed-size array with length equal to the byte count of the file given by path
. The contents of the array are the contents of the file.
path
is absolute or relative to the current file, just like @import
.
See also:
@enumToInt
@enumToInt(enum_or_tagged_union: var) var
Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value.
If there is only one possible enum value, the resut is a comptime_int
known at comptime.
See also:
@errorName
@errorName(err: anyerror) []const u8
This function returns the string representation of an error. The string representation of error.OutOfMem
is "OutOfMem"
.
If there are no calls to @errorName
in an entire application, or all calls have a compile-time known value for err
, then no error name table will be generated.
@errorReturnTrace
@errorReturnTrace() ?*builtin.StackTrace
If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a stack trace object. Otherwise returns null
.
@errorToInt
@errorToInt(err: var) @IntType(false, @sizeOf(anyerror) * 8)
Supports the following types:
Converts an error to the integer representation of an error.
It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
See also:
@errSetCast
@errSetCast(comptime T: DestType, value: var) DestType
Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected Undefined Behavior.
@export
@export(comptime name: []const u8, target: var, linkage: builtin.GlobalLinkage) []const u8
Creates a symbol in the output object file.
This function can be called from a comptime block to conditionally export symbols. When target
is a function with the C calling convention and linkage
is Strong
, this is equivalent to the export
keyword used on a function:
test.zig
const builtin = @import("builtin");
comptime {
@export("foo", internalName, builtin.GlobalLinkage.Strong);
}
extern fn internalName() void {}
$ zig build-obj test.zig
This is equivalent to:
test.zig
export fn foo() void {}
$ zig build-obj test.zig
Note that even when using export
, @"foo"
syntax can be used to choose any string for the symbol name:
test.zig
export fn @"A function name that is a complete sentence."() void {}
$ zig build-obj test.zig
When looking at the resulting object, you can see the symbol is used verbatim:
- 00000000000001f0 T A function name that is a complete sentence.
See also:
@fence
@fence(order: AtomicOrder)
The fence
function is used to introduce happens-before edges between operations.
AtomicOrder
can be found with @import("builtin").AtomicOrder
.
See also:
@field
@field(lhs: var, comptime field_name: []const u8) (field)
Preforms field access equivalent to lhs.field_name
, except instead of the field "field_name"
, it accesses the field named by the string value of field_name
.
@fieldParentPtr
@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,
field_ptr: *T) *ParentType
Given a pointer to a field, returns the base pointer of a struct.
@floatCast
@floatCast(comptime DestType: type, value: var) DestType
Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision.
@floatToInt
@floatToInt(comptime DestType: type, float: var) DestType
Converts the integer part of a floating point number to the destination type.
If the integer part of the floating point number cannot fit in the destination type, it invokes safety-checked Undefined Behavior.
See also:
@frameAddress
@frameAddress() usize
This function returns the base pointer of the current stack frame.
The implications of this are target specific and not consistent across all platforms. The frame address may not be available in release mode due to aggressive optimizations.
This function is only valid within function scope.
@handle
@handle()
This function returns a promise->T
type, where T
is the return type of the async function in scope.
This function is only valid within an async function scope.
@import
@import(comptime path: []u8) type
This function finds a zig file corresponding to path
and adds it to the build, if it is not already added.
Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. @import
returns the struct type corresponding to the file.
Declarations which have the pub
keyword may be referenced from a different source file than the one they are declared in.
path
can be a relative or absolute path, or it can be the name of a package. If it is a relative path, it is relative to the file that contains the @import
function call.
The following packages are always available:
@import("std")
- Zig Standard Library@import("builtin")
- Compiler-provided types and variables. The commandzig builtin
outputs the source to stdout for reference.
See also:
@inlineCall
@inlineCall(function: X, args: ...) Y
This calls a function, in the same way that invoking an expression with parentheses does:
test.zig
const assert = @import("std").debug.assert;
test "inline function call" {
assert(@inlineCall(add, 3, 9) == 12);
}
fn add(a: i32, b: i32) i32 { return a + b; }
$ zig test test.zig
Test 1/1 inline function call...OK
All tests passed.
Unlike a normal function call, however, @inlineCall
guarantees that the call will be inlined. If the call cannot be inlined, a compile error is emitted.
See also:
@intCast
@intCast(comptime DestType: type, int: var) DestType
Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in safety-protected Undefined Behavior.
@intToEnum
@intToEnum(comptime DestType: type, int_value: @TagType(DestType)) DestType
Converts an integer into an enum value.
Attempting to convert an integer which represents no value in the chosen enum type invokes safety-checked Undefined Behavior.
See also:
@intToError
@intToError(value: @IntType(false, @sizeOf(anyerror) * 8)) anyerror
Converts from the integer representation of an error into The Global Error Set type.
It is generally recommended to avoid this cast, as the integer representation of an error is not stable across source code changes.
Attempting to convert an integer that does not correspond to any error results in safety-protected Undefined Behavior.
See also:
@intToFloat
@intToFloat(comptime DestType: type, int: var) DestType
Converts an integer to the closest floating point representation. To convert the other way, use @floatToInt. This cast is always safe.
@intToPtr
@intToPtr(comptime DestType: type, address: usize) DestType
Converts an integer to a pointer. To convert the other way, use @ptrToInt.
If the destination pointer type does not allow address zero and address
is zero, this invokes safety-checked Undefined Behavior.
@IntType
@IntType(comptime is_signed: bool, comptime bit_count: u16) type
This function returns an integer type with the given signness and bit count. The maximum bit count for an integer type is 65535
.
@memberCount
@memberCount(comptime T: type) comptime_int
This function returns the number of members in a struct, enum, or union type.
The result is a compile time constant.
It does not include functions, variables, or constants.
@memberName
@memberName(comptime T: type, comptime index: usize) [N]u8
Returns the field name of a struct, union, or enum.
The result is a compile time constant.
It does not include functions, variables, or constants.
@memberType
@memberType(comptime T: type, comptime index: usize) type
Returns the field type of a struct or union.
@memcpy
@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize)
This function copies bytes from one region of memory to another. dest
and source
are both pointers and must not overlap.
This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
for (source[0..byte_count]) |b, i| dest[i] = b;
The optimizer is intelligent enough to turn the above snippet into a memcpy.
There is also a standard library function for this:
const mem = @import("std").mem;
mem.copy(u8, dest[0..byte_count], source[0..byte_count]);
@memset
@memset(dest: [*]u8, c: u8, byte_count: usize)
This function sets a region of memory to c
. dest
is a pointer.
This function is a low level intrinsic with no safety mechanisms. Most code should not use this function, instead using something like this:
for (dest[0..byte_count]) |*b| b.* = c;
The optimizer is intelligent enough to turn the above snippet into a memset.
There is also a standard library function for this:
const mem = @import("std").mem;
mem.set(u8, dest, c);
@mod
@mod(numerator: T, denominator: T) T
Modulus division. For unsigned integers this is the same as numerator % denominator
. Caller guarantees denominator > 0
.
@mod(-5, 3) == 1
@divFloor(a, b) + @mod(a, b) == a
For a function that returns an error code, see @import("std").math.mod
.
See also:
@mulWithOverflow
@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool
Performs result.* = a * b
. If overflow or underflow occurs, stores the overflowed bits in result
and returns true
. If no overflow or underflow occurs, returns false
.
@newStackCall
@newStackCall(new_stack: []u8, function: var, args: ...) var
This calls a function, in the same way that invoking an expression with parentheses does. However, instead of using the same stack as the caller, the function uses the stack provided in the new_stack
parameter.
test.zig
const std = @import("std");
const assert = std.debug.assert;
var new_stack_bytes: [1024]u8 = undefined;
test "calling a function with a new stack" {
const arg = 1234;
const a = @newStackCall(new_stack_bytes[0..512], targetFunction, arg);
const b = @newStackCall(new_stack_bytes[512..], targetFunction, arg);
_ = targetFunction(arg);
assert(arg == 1234);
assert(a < b);
}
fn targetFunction(x: i32) usize {
assert(x == 1234);
var local_variable: i32 = 42;
const ptr = &local_variable;
ptr.* += 1;
assert(local_variable == 43);
return @ptrToInt(ptr);
}
$ zig test test.zig
Test 1/1 calling a function with a new stack...OK
All tests passed.
@noInlineCall
@noInlineCall(function: var, args: ...) var
This calls a function, in the same way that invoking an expression with parentheses does:
test.zig
const assert = @import("std").debug.assert;
test "noinline function call" {
assert(@noInlineCall(add, 3, 9) == 12);
}
fn add(a: i32, b: i32) i32 {
return a + b;
}
$ zig test test.zig
Test 1/1 noinline function call...OK
All tests passed.
Unlike a normal function call, however, @noInlineCall
guarantees that the call will not be inlined. If the call must be inlined, a compile error is emitted.
See also:
@OpaqueType
@OpaqueType() type
Creates a new type with an unknown (but non-zero) size and alignment.
This is typically used for type safety when interacting with C code that does not expose struct details. Example:
test.zig
const Derp = @OpaqueType();
const Wat = @OpaqueType();
extern fn bar(d: *Derp) void;
export fn foo(w: *Wat) void {
bar(w);
}
test "call foo" {
foo(undefined);
}
$ zig test test.zig
/home/andy/dev/zig/docgen_tmp/test.zig:6:9: error: expected type '*Derp', found '*Wat'
bar(w);
^
/home/andy/dev/zig/docgen_tmp/test.zig:6:9: note: pointer type child 'Wat' cannot cast into pointer type child 'Derp'
bar(w);
^
@panic
@panic(message: []const u8) noreturn
Invokes the panic handler function. By default the panic handler function calls the public panic
function exposed in the root source file, or if there is not one specified, invokes the one provided in std/special/panic.zig
.
Generally it is better to use @import("std").debug.panic
. However, @panic
can be useful for 2 scenarios:
- From library code, calling the programmer's panic function if they exposed one in the root source file.
- When mixing C and Zig code, calling the canonical panic implementation across multiple .o files.
See also:
@popCount
@popCount(integer: var) var
Counts the number of bits set in an integer.
If integer
is known at comptime, the return type is comptime_int
. Otherwise, the return type is an unsigned integer with the minimum number of bits that can represent the bit count of the integer type.
See also:
@ptrCast
@ptrCast(comptime DestType: type, value: var) DestType
Converts a pointer of one type to a pointer of another type.
Optional Pointers are allowed. Casting an optional pointer which is null to a non-optional pointer invokes safety-checked Undefined Behavior.
@ptrToInt
@ptrToInt(value: var) usize
Converts value
to a usize
which is the address of the pointer. value
can be one of these types:
*T
?*T
fn()
?fn()
To convert the other way, use @intToPtr
@rem
@rem(numerator: T, denominator: T) T
Remainder division. For unsigned integers this is the same as numerator % denominator
. Caller guarantees denominator > 0
.
@rem(-5, 3) == -2
@divTrunc(a, b) + @rem(a, b) == a
For a function that returns an error code, see @import("std").math.rem
.
See also:
@returnAddress
@returnAddress() usize
This function returns the address of the next machine code instruction that will be executed when the current function returns.
The implications of this are target specific and not consistent across all platforms.
This function is only valid within function scope. If the function gets inlined into a calling function, the returned address will apply to the calling function.
@setAlignStack
@setAlignStack(comptime alignment: u29)
Ensures that a function will have a stack alignment of at least alignment
bytes.
@setCold
@setCold(is_cold: bool)
Tells the optimizer that a function is rarely called.
@setEvalBranchQuota
@setEvalBranchQuota(new_quota: usize)
Changes the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.
If the new_quota
is smaller than the default quota (1000
) or a previously explicitly set quota, it is ignored.
Example:
test.zig
test "foo" {
comptime {
var i = 0;
while (i < 1001) : (i += 1) {}
}
}
$ zig test test.zig
/home/andy/dev/zig/docgen_tmp/test.zig:4:9: error: evaluation exceeded 1000 backwards branches
while (i < 1001) : (i += 1) {}
^
Now we use @setEvalBranchQuota
:
test.zig
test "foo" {
comptime {
@setEvalBranchQuota(1001);
var i = 0;
while (i < 1001) : (i += 1) {}
}
}
$ zig test test.zig
Test 1/1 foo...OK
All tests passed.
See also:
@setFloatMode
@setFloatMode(mode: @import("builtin").FloatMode)
Sets the floating point mode of the current scope. Possible values are:
pub const FloatMode = enum {
Strict,
Optimized,
};
Strict
(default) - Floating point operations follow strict IEEE compliance.Optimized
- Floating point operations may do all of the following:- Assume the arguments and result are not NaN. Optimizations are required to retain defined behavior over NaNs, but the value of the result is undefined.
- Assume the arguments and result are not +/-Inf. Optimizations are required to retain defined behavior over +/-Inf, but the value of the result is undefined.
- Treat the sign of a zero argument or result as insignificant.
- Use the reciprocal of an argument rather than perform division.
- Perform floating-point contraction (e.g. fusing a multiply followed by an addition into a fused multiply-and-add).
- Perform algebraically equivalent transformations that may change results in floating point (e.g. reassociate). This is equivalent to
-ffast-math
in GCC.
The floating point mode is inherited by child scopes, and can be overridden in any scope. You can set the floating point mode in a struct or module scope by using a comptime block.
See also:
@setGlobalLinkage
@setGlobalLinkage(global_variable_name, comptime linkage: GlobalLinkage)
GlobalLinkage
can be found with @import("builtin").GlobalLinkage
.
See also:
@setRuntimeSafety
@setRuntimeSafety(safety_on: bool)
Sets whether runtime safety checks are enabled for the scope that contains the function call.
test.zig
test "@setRuntimeSafety" {
// The builtin applies to the scope that it is called in. So here, integer overflow
// will not be caught in ReleaseFast and ReleaseSmall modes:
// var x: u8 = 255;
// x += 1; // undefined behavior in ReleaseFast/ReleaseSmall modes.
{
// However this block has safety enabled, so safety checks happen here,
// even in ReleaseFast and ReleaseSmall modes.
@setRuntimeSafety(true);
var x: u8 = 255;
x += 1;
{
// The value can be overridden at any scope. So here integer overflow
// would not be caught in any build mode.
@setRuntimeSafety(false);
// var x: u8 = 255;
// x += 1; // undefined behavior in all build modes.
}
}
}
$ zig test test.zig --release-fast
Test 1/1 @setRuntimeSafety...integer overflow
Tests failed. Use the following command to reproduce the failure:
/home/andy/dev/zig/docgen_tmp/test
@shlExact
@shlExact(value: T, shift_amt: Log2T) T
Performs the left shift operation (<<
). Caller guarantees that the shift will not shift any 1 bits out.
The type of shift_amt
is an unsigned integer with log2(T.bit_count)
bits. This is because shift_amt >= T.bit_count
is undefined behavior.
See also:
@shlWithOverflow
@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool
Performs result.* = a << b
. If overflow or underflow occurs, stores the overflowed bits in result
and returns true
. If no overflow or underflow occurs, returns false
.
The type of shift_amt
is an unsigned integer with log2(T.bit_count)
bits. This is because shift_amt >= T.bit_count
is undefined behavior.
See also:
@shrExact
@shrExact(value: T, shift_amt: Log2T) T
Performs the right shift operation (>>
). Caller guarantees that the shift will not shift any 1 bits out.
The type of shift_amt
is an unsigned integer with log2(T.bit_count)
bits. This is because shift_amt >= T.bit_count
is undefined behavior.
See also:
@sizeOf
@sizeOf(comptime T: type) comptime_int
This function returns the number of bytes it takes to store T
in memory. The result is a target-specific compile time constant.
This size may contain padding bytes. If there were two consecutive T in memory, this would be the offset in bytes between element at index 0 and the element at index 1. For integer, consider whether you want to use @sizeOf(T)
or @typeInfo(T).Int.bits
.
See also:
@sliceToBytes
@sliceToBytes(value: var) []u8
Converts a slice or array to a slice of u8
. The resulting slice has the same pointer properties as the parameter.
@sqrt
@sqrt(comptime T: type, value: T) T
Performs the square root of a floating point number. Uses a dedicated hardware instruction when available. Currently only supports f32 and f64 at runtime. f128 at runtime is TODO.
This is a low-level intrinsic. Most code can use std.math.sqrt
instead.
@subWithOverflow
@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool
Performs result.* = a - b
. If overflow or underflow occurs, stores the overflowed bits in result
and returns true
. If no overflow or underflow occurs, returns false
.
@tagName
@tagName(value: var) []const u8
Converts an enum value or union value to a slice of bytes representing the name.
@TagType
@TagType(T: type) type
For an enum, returns the integer type that is used to store the enumeration value.
For a union, returns the enum type that is used to store the tag value.
@This
@This() type
Returns the innermost struct or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:
test.zig
const std = @import("std");
const assert = std.debug.assert;
test "@This()" {
var items = []i32{ 1, 2, 3, 4 };
const list = List(i32){ .items = items[0..] };
assert(list.length() == 4);
}
fn List(comptime T: type) type {
return struct {
const Self = @This();
items: []T,
fn length(self: Self) usize {
return self.items.len;
}
};
}
$ zig test test.zig
Test 1/1 @This()...OK
All tests passed.
When @This()
is used at global scope, it returns a reference to the current import. There is a proposal to remove the import type and use an empty struct type instead. See #1047 for details.
@truncate
@truncate(comptime T: type, integer: var) T
This function truncates bits from an integer type, resulting in a smaller integer type.
The following produces a crash in Debug mode and Undefined Behavior in ReleaseFast mode:
const a: u16 = 0xabcd;
const b: u8 = u8(a);
However this is well defined and working code:
const a: u16 = 0xabcd;
const b: u8 = @truncate(u8, a);
// b is now 0xcd
This function always truncates the significant bits of the integer, regardless of endianness on the target platform.
If T
is comptime_int
, then this is semantically equivalent to an implicit cast.
@typeId
@typeId(comptime T: type) @import("builtin").TypeId
Returns which kind of type something is. Possible values:
pub const TypeId = enum {
Type,
Void,
Bool,
NoReturn,
Int,
Float,
Pointer,
Array,
Struct,
ComptimeFloat,
ComptimeInt,
Undefined,
Null,
Optional,
ErrorUnion,
Error,
Enum,
Union,
Fn,
Block,
BoundFn,
ArgTuple,
Opaque,
};
@typeInfo
@typeInfo(comptime T: type) @import("builtin").TypeInfo
Returns information on the type. Returns a value of the following union:
pub const TypeInfo = union(TypeId) {
Type: void,
Void: void,
Bool: void,
NoReturn: void,
Int: Int,
Float: Float,
Pointer: Pointer,
Array: Array,
Struct: Struct,
ComptimeFloat: void,
ComptimeInt: void,
Undefined: void,
Null: void,
Optional: Optional,
ErrorUnion: ErrorUnion,
ErrorSet: ErrorSet,
Enum: Enum,
Union: Union,
Fn: Fn,
BoundFn: Fn,
ArgTuple: void,
Opaque: void,
Promise: Promise,
Vector: Vector,
EnumLiteral: void,
pub const Int = struct {
is_signed: bool,
bits: comptime_int,
};
pub const Float = struct {
bits: comptime_int,
};
pub const Pointer = struct {
size: Size,
is_const: bool,
is_volatile: bool,
alignment: comptime_int,
child: type,
is_allowzero: bool,
pub const Size = enum {
One,
Many,
Slice,
C,
};
};
pub const Array = struct {
len: comptime_int,
child: type,
};
pub const ContainerLayout = enum {
Auto,
Extern,
Packed,
};
pub const StructField = struct {
name: []const u8,
offset: ?comptime_int,
field_type: type,
};
pub const Struct = struct {
layout: ContainerLayout,
fields: []StructField,
defs: []Definition,
};
pub const Optional = struct {
child: type,
};
pub const ErrorUnion = struct {
error_set: type,
payload: type,
};
pub const Error = struct {
name: []const u8,
value: comptime_int,
};
pub const ErrorSet = ?[]Error;
pub const EnumField = struct {
name: []const u8,
value: comptime_int,
};
pub const Enum = struct {
layout: ContainerLayout,
tag_type: type,
fields: []EnumField,
defs: []Definition,
};
pub const UnionField = struct {
name: []const u8,
enum_field: ?EnumField,
field_type: type,
};
pub const Union = struct {
layout: ContainerLayout,
tag_type: ?type,
fields: []UnionField,
defs: []Definition,
};
pub const CallingConvention = enum {
Unspecified,
C,
Cold,
Naked,
Stdcall,
Async,
};
pub const FnArg = struct {
is_generic: bool,
is_noalias: bool,
arg_type: ?type,
};
pub const Fn = struct {
calling_convention: CallingConvention,
is_generic: bool,
is_var_args: bool,
return_type: ?type,
async_allocator_type: ?type,
args: []FnArg,
};
pub const Promise = struct {
child: ?type,
};
pub const Vector = struct {
len: comptime_int,
child: type,
};
pub const Definition = struct {
name: []const u8,
is_pub: bool,
data: Data,
pub const Data = union(enum) {
Type: type,
Var: type,
Fn: FnDef,
pub const FnDef = struct {
fn_type: type,
inline_type: Inline,
calling_convention: CallingConvention,
is_var_args: bool,
is_extern: bool,
is_export: bool,
lib_name: ?[]const u8,
return_type: type,
arg_names: [][] const u8,
pub const Inline = enum {
Auto,
Always,
Never,
};
};
};
};
};
For structs, unions, enums, and error sets, the fields are guaranteed to be in the same order as declared. For declarations, the order is unspecified.
@typeName
@typeName(T: type) [N]u8
This function returns the string representation of a type, as an array. It is equivalent to a string literal of the type name.
@typeOf
@typeOf(expression) type
This function returns a compile-time constant, which is the type of the expression passed as an argument. The expression is evaluated.
@Vector
@Vector(comptime len: u32, comptime ElemType: type) type
This function returns a vector type for SIMD.