Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
βŒ€
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/01-assignment.mdx
--- pagination_prev: getting-started/running-tests --- import CodeBlock from "@theme/CodeBlock"; import Assignment from "!!raw-loader!./01.assignment.zig"; import Undefined from "!!raw-loader!./01.undefined.zig"; # Assignment Value assignment has the following syntax: `(const|var) identifier[: type] = value`. - `const` indicates that `identifier` is a **constant** that stores an immutable value. - `var` indicates that `identifier` is a **variable** that stores a mutable value. - `: type` is a type annotation for `identifier`, and may be omitted if the data type of `value` can be inferred. <CodeBlock language="zig">{Assignment}</CodeBlock> Constants and variables _must_ have a value. If no known value can be given, the [`undefined`](https://ziglang.org/documentation/master/#undefined) value, which coerces to any type, may be used as long as a type annotation is provided. <CodeBlock language="zig">{Undefined}</CodeBlock> Where possible, `const` values are preferred over `var` values.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/09.switch-expression.zig
// hide-start const expect = @import("std").testing.expect; // hide-end test "switch expression" { var x: i8 = 10; x = switch (x) { -1...1 => -x, 10, 100 => @divExact(x, 10), else => x, }; try expect(x == 1); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/04-while-loops.mdx
import CodeBlock from "@theme/CodeBlock"; import While from "!!raw-loader!./04.while.zig"; import WhileContinueExpression from "!!raw-loader!./04.while-continue-expression.zig"; import WhileContinue from "!!raw-loader!./04.while-continue.zig"; import WhileBreak from "!!raw-loader!./04.while-break.zig"; # While loops Zig's while loop has three parts - a condition, a block and a continue expression. Without a continue expression. <CodeBlock language="zig">{While}</CodeBlock> With a continue expression. <CodeBlock language="zig">{WhileContinueExpression}</CodeBlock> With a `continue`. <CodeBlock language="zig">{WhileContinue}</CodeBlock> With a `break`. <CodeBlock language="zig">{WhileBreak}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/06-functions.mdx
import CodeBlock from "@theme/CodeBlock"; import Functions from "!!raw-loader!./06.functions.zig"; import FunctionsRecursion from "!!raw-loader!./06.functions-recursion.zig"; # Functions **All function arguments are immutable** - if a copy is desired the user must explicitly make one. Unlike variables, which are snake_case, functions are camelCase. Here's an example of declaring and calling a simple function. <CodeBlock language="zig">{Functions}</CodeBlock> Recursion is allowed: <CodeBlock language="zig">{FunctionsRecursion}</CodeBlock> When recursion happens, the compiler is no longer able to work out the maximum stack size, which may result in unsafe behaviour - a stack overflow. Details on how to achieve safe recursion will be covered in future. Values can be ignored using `_` instead of a variable or const declaration. This does not work at the global scope (i.e. it only works inside functions and blocks) and is useful for ignoring the values returned from functions if you do not need them. ```zig _ = 10; ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-set-coercion.zig
// hide-start const expect = @import("std").testing.expect; const FileOpenError = error{ AccessDenied, OutOfMemory, FileNotFound, }; // hide-end const AllocationError = error{OutOfMemory}; test "coerce error from a subset to a superset" { const err: FileOpenError = AllocationError.OutOfMemory; try expect(err == FileOpenError.OutOfMemory); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/14.slices-2.zig
// hide-start const expect = @import("std").testing.expect; // hide-end test "slices 2" { const array = [_]u8{ 1, 2, 3, 4, 5 }; const slice = array[0..3]; try expect(@TypeOf(slice) == *const [3]u8); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.errdefer.zig
// hide-start const expect = @import("std").testing.expect; fn failingFunction() error{Oops}!void { return error.Oops; } //hide-end var problems: u32 = 98; fn failFnCounter() error{Oops}!void { errdefer problems += 1; try failingFunction(); } test "errdefer" { failFnCounter() catch |err| { try expect(err == error.Oops); try expect(problems == 99); return; }; }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/01.assignment.zig
const constant: i32 = 5; // signed 32-bit constant var variable: u32 = 5000; // unsigned 32-bit variable // @as performs an explicit type coercion const inferred_constant = @as(i32, 5); var inferred_variable = @as(u32, 5000);
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/20-labelled-blocks.md
# Labelled Blocks Blocks in Zig are expressions and can be given labels, which are used to yield values. Here, we are using a label called `blk`. Blocks yield values, meaning they can be used in place of a value. The value of an empty block `{}` is a value of the type `void`. ```zig test "labelled blocks" { const count = blk: { var sum: u32 = 0; var i: u32 = 0; while (i < 10) : (i += 1) sum += i; break :blk sum; }; try expect(count == 45); try expect(@TypeOf(count) == u32); } ``` This can be seen as being equivalent to C's `i++`. <!--no_test--> ```zig blk: { const tmp = i; i += 1; break :blk tmp; } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/22-loops-as-expressions.md
# Loops as Expressions Like `return`, `break` accepts a value. This can be used to yield a value from a loop. Loops in Zig also have an `else` branch, which is evaluated when the loop is not exited with a `break`. ```zig fn rangeHasNumber(begin: usize, end: usize, number: usize) bool { var i = begin; return while (i < end) : (i += 1) { if (i == number) { break true; } } else false; } test "while loop expression" { try expect(rangeHasNumber(0, 10, 3)); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/04.while-break.zig
// hide-start const expect = @import("std").testing.expect; // hide-end test "while with break" { var sum: u8 = 0; var i: u8 = 0; while (i <= 3) : (i += 1) { if (i == 2) break; sum += i; } try expect(sum == 1); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/19.floats-literals.zig
const floating_point: f64 = 123.0E+77; const another_float: f64 = 123.0; const yet_another: f64 = 123.0e+77; const hex_floating_point: f64 = 0x103.70p-5; const another_hex_float: f64 = 0x103.70; const yet_another_hex_float: f64 = 0x103.70P-5;
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/12-pointer-sized-integers.md
# Pointer Sized Integers `usize` and `isize` are given as unsigned and signed integers which are the same size as pointers. ```zig test "usize" { try expect(@sizeOf(usize) == @sizeOf(*u8)); try expect(@sizeOf(isize) == @sizeOf(*u8)); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/09-switch.mdx
import CodeBlock from "@theme/CodeBlock"; import SwitchStatement from "!!raw-loader!./09.switch-statement.zig"; import SwitchExpression from "!!raw-loader!./09.switch-expression.zig"; # Switch Zig's `switch` works as both a statement and an expression. The types of all branches must coerce to the type which is being switched upon. All possible values must have an associated branch - values cannot be left out. Cases cannot fall through to other branches. An example of a switch statement. The else is required to satisfy the exhaustiveness of this switch. <CodeBlock language="zig">{SwitchStatement}</CodeBlock> Here is the former, but as a switch expression. <CodeBlock language="zig">{SwitchExpression}</CodeBlock> :::info Now is the perfect time to use what you've learned and [solve a problem together](/posts/fizz-buzz). :::
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/24-comptime.md
# Comptime Blocks of code may be forcibly executed at compile time using the [`comptime`](https://ziglang.org/documentation/master/#comptime) keyword. In this example, the variables x and y are equivalent. ```zig test "comptime blocks" { var x = comptime fibonacci(10); _ = x; var y = comptime blk: { break :blk fibonacci(10); }; _ = y; } ``` Integer literals are of the type `comptime_int`. These are special in that they have no size (they cannot be used at runtime!), and they have arbitrary precision. `comptime_int` values coerce to any integer type that can hold them. They also coerce to floats. Character literals are of this type. ```zig test "comptime_int" { const a = 12; const b = a + 10; const c: u4 = a; _ = c; const d: f32 = b; _ = d; } ``` `comptime_float` is also available, which internally is an `f128`. These cannot be coerced to integers, even if they hold an integer value. Types in Zig are values of the type `type`. These are available at compile time. We have previously encountered them by checking [`@TypeOf`](https://ziglang.org/documentation/master/#TypeOf) and comparing with other types, but we can do more. ```zig test "branching on types" { const a = 5; const b: if (a < 10) f32 else i32 = 5; _ = b; } ``` Function parameters in Zig can be tagged as being [`comptime`](https://ziglang.org/documentation/master/#comptime). This means that the value passed to that function parameter must be known at compile time. Let's make a function that returns a type. Notice how this function is PascalCase, as it returns a type. ```zig fn Matrix( comptime T: type, comptime width: comptime_int, comptime height: comptime_int, ) type { return [height][width]T; } test "returning a type" { try expect(Matrix(f32, 4, 4) == [4][4]f32); } ``` We can reflect upon types using the built-in [`@typeInfo`](https://ziglang.org/documentation/master/#typeInfo), which takes in a `type` and returns a tagged union. This tagged union type can be found in [`std.builtin.TypeInfo`](https://ziglang.org/documentation/master/std/#std;builtin.TypeInfo) (info on how to make use of imports and std later). ```zig fn addSmallInts(comptime T: type, a: T, b: T) T { return switch (@typeInfo(T)) { .ComptimeInt => a + b, .Int => |info| if (info.bits <= 16) a + b else @compileError("ints too large"), else => @compileError("only ints accepted"), }; } test "typeinfo switch" { const x = addSmallInts(u16, 20, 30); try expect(@TypeOf(x) == u16); try expect(x == 50); } ``` We can use the [`@Type`](https://ziglang.org/documentation/master/#Type) function to create a type from a [`@typeInfo`](https://ziglang.org/documentation/master/#typeInfo). [`@Type`](https://ziglang.org/documentation/master/#Type) is implemented for most types but is notably unimplemented for enums, unions, functions, and structs. Here anonymous struct syntax is used with `.{}`, because the `T` in `T{}` can be inferred. Anonymous structs will be covered in detail later. In this example we will get a compile error if the `Int` tag isn't set. ```zig fn GetBiggerInt(comptime T: type) type { return @Type(.{ .Int = .{ .bits = @typeInfo(T).Int.bits + 1, .signedness = @typeInfo(T).Int.signedness, }, }); } test "@Type" { try expect(GetBiggerInt(u8) == u9); try expect(GetBiggerInt(i31) == i32); } ``` Returning a struct type is how you make generic data structures in Zig. The usage of [`@This`](https://ziglang.org/documentation/master/#This) is required here, which gets the type of the innermost struct, union, or enum. Here [`std.mem.eql`](https://ziglang.org/documentation/master/std/#std;mem.eql) is also used which compares two slices. ```zig fn Vec( comptime count: comptime_int, comptime T: type, ) type { return struct { data: [count]T, const Self = @This(); fn abs(self: Self) Self { var tmp = Self{ .data = undefined }; for (self.data, 0..) |elem, i| { tmp.data[i] = if (elem < 0) -elem else elem; } return tmp; } fn init(data: [count]T) Self { return Self{ .data = data }; } }; } const eql = @import("std").mem.eql; test "generic vector" { const x = Vec(3, f32).init([_]f32{ 10, -10, 5 }); const y = x.abs(); try expect(eql(f32, &y.data, &[_]f32{ 10, 10, 5 })); } ``` The types of function parameters can also be inferred by using `anytype` in place of a type. [`@TypeOf`](https://ziglang.org/documentation/master/#TypeOf) can then be used on the parameter. ```zig fn plusOne(x: anytype) @TypeOf(x) { return x + 1; } test "inferred function parameter" { try expect(plusOne(@as(u32, 1)) == 2); } ``` Comptime also introduces the operators `++` and `**` for concatenating and repeating arrays and slices. These operators do not work at runtime. ```zig test "++" { const x: [4]u8 = undefined; const y = x[0..]; const a: [6]u8 = undefined; const b = a[0..]; const new = y ++ b; try expect(new.len == 10); } test "**" { const pattern = [_]u8{ 0xCC, 0xAA }; const memory = pattern ** 3; try expect(eql(u8, &memory, &[_]u8{ 0xCC, 0xAA, 0xCC, 0xAA, 0xCC, 0xAA })); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/17.union-tagged.zig
// hide-start const expect = @import("std").testing.expect; //hide-end const Tag = enum { a, b, c }; const Tagged = union(Tag) { a: u8, b: f32, c: bool }; test "switch on tagged union" { var value = Tagged{ .b = 1.5 }; switch (value) { .a => |*byte| byte.* += 1, .b => |*float| float.* *= 2, .c => |*b| b.* = !b.*, } try expect(value.b == 3); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/26-inline-loops.md
# Inline Loops `inline` loops are unrolled, and allow some things to happen that only work at compile time. Here we use a [`for`](https://ziglang.org/documentation/master/#inline-for), but a [`while`](https://ziglang.org/documentation/master/#inline-while) works similarly. ```zig test "inline for" { const types = [_]type{ i32, f32, u8, bool }; var sum: usize = 0; inline for (types) |T| sum += @sizeOf(T); try expect(sum == 10); } ``` Using these for performance reasons is inadvisable unless you've tested that explicitly unrolling is faster; the compiler tends to make better decisions here than you.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/07.defer-multi.zig
// hide-start const expect = @import("std").testing.expect; // hide-end test "multi defer" { var x: f32 = 5; { defer x += 2; defer x /= 2; } try expect(x == 4.5); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/10.switch-unreachable.zig
// hide-start const expect = @import("std").testing.expect; // hide-end fn asciiToUpper(x: u8) u8 { return switch (x) { 'a'...'z' => x + 'A' - 'a', 'A'...'Z' => x, else => unreachable, }; } test "unreachable switch" { try expect(asciiToUpper('a') == 'A'); try expect(asciiToUpper('A') == 'A'); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/28-anonymous-structs.md
# Anonymous Structs The struct type may be omitted from a struct literal. These literals may coerce to other struct types. ```zig test "anonymous struct literal" { const Point = struct { x: i32, y: i32 }; var pt: Point = .{ .x = 13, .y = 67, }; try expect(pt.x == 13); try expect(pt.y == 67); } ``` Anonymous structs may be completely anonymous i.e. without being coerced to another struct type. ```zig test "fully anonymous struct" { try dump(.{ .int = @as(u32, 1234), .float = @as(f64, 12.34), .b = true, .s = "hi", }); } fn dump(args: anytype) !void { try expect(args.int == 1234); try expect(args.float == 12.34); try expect(args.b); try expect(args.s[0] == 'h'); try expect(args.s[1] == 'i'); } ``` <!-- TODO: mention tuple slicing when it's implemented --> Anonymous structs without field names may be created and are referred to as **tuples**. These have many of the properties that arrays do; tuples can be iterated over, indexed, can be used with the `++` and `**` operators, and have a len field. Internally, these have numbered field names starting at `"0"`, which may be accessed with the special syntax `@"0"` which acts as an escape for the syntax - things inside `@""` are always recognised as identifiers. An `inline` loop must be used to iterate over the tuple here, as the type of each tuple field may differ. ```zig test "tuple" { const values = .{ @as(u32, 1234), @as(f64, 12.34), true, "hi", } ++ .{false} ** 2; try expect(values[0] == 1234); try expect(values[4] == false); inline for (values, 0..) |v, i| { if (i != 2) continue; try expect(v); } try expect(values.len == 6); try expect(values.@"3"[0] == 'h'); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/10-runtime-safety.mdx
import CodeBlock from "@theme/CodeBlock"; import SwitchUnreachable from "!!raw-loader!./10.switch-unreachable.zig"; # Runtime Safety Zig provides a level of safety, where problems may be found during execution. Safety can be left on, or turned off. Zig has many cases of so-called **detectable illegal behaviour**, meaning that illegal behaviour will be caught (causing a panic) with safety on, but will result in undefined behaviour with safety off. Users are strongly recommended to develop and test their software with safety on, despite its speed penalties. For example, runtime safety protects you from out of bounds indices. ```zig test "out of bounds" { const a = [3]u8{ 1, 2, 3 }; var index: u8 = 5; const b = a[index]; _ = b; } ``` ``` test "out of bounds"...index out of bounds .\tests.zig:43:14: 0x7ff698cc1b82 in test "out of bounds" (test.obj) const b = a[index]; ^ ``` The user may disable runtime safety for the current block using the built-in function [`@setRuntimeSafety`](https://ziglang.org/documentation/master/#setRuntimeSafety). ```zig test "out of bounds, no safety" { @setRuntimeSafety(false); const a = [3]u8{ 1, 2, 3 }; var index: u8 = 5; const b = a[index]; _ = b; } ``` Safety is off for some build modes (to be discussed later). # Unreachable [`unreachable`](https://ziglang.org/documentation/master/#unreachable) is an assertion to the compiler that this statement will not be reached. It can tell the compiler that a branch is impossible, which the optimiser can then take advantage of. Reaching an [`unreachable`](https://ziglang.org/documentation/master/#unreachable) is detectable illegal behaviour. As it is of the type [`noreturn`](https://ziglang.org/documentation/master/#noreturn), it is compatible with all other types. Here it coerces to u32. ```zig test "unreachable" { const x: i32 = 1; const y: u32 = if (x == 2) 5 else unreachable; _ = y; } ``` ``` test "unreachable"...reached unreachable code .\tests.zig:211:39: 0x7ff7e29b2049 in test "unreachable" (test.obj) const y: u32 = if (x == 2) 5 else unreachable; ^ ``` Here is an unreachable being used in a switch. <CodeBlock language="zig">{SwitchUnreachable}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/13-many-item-pointers.md
# Many-item Pointers Sometimes, you may have a pointer to an unknown number of elements. `[*]T` is the solution for this, which works like `*T` but also supports indexing syntax, pointer arithmetic, and slicing. Unlike `*T`, it cannot point to a type that does not have a known size. `*T` coerces to `[*]T`. These many pointers may point to any amount of elements, including 0 and 1.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/11-pointers.mdx
import CodeBlock from "@theme/CodeBlock"; import Pointers from "!!raw-loader!./11.pointers.zig"; # Pointers Normal pointers in Zig cannot have 0 or null as a value. They follow the syntax `*T`, where `T` is the child type. Referencing is done with `&variable`, and dereferencing is done with `variable.*`. <CodeBlock language="zig">{Pointers}</CodeBlock> Trying to set a `*T` to the value 0 is detectable illegal behaviour. <!--fail_test--> ```zig test "naughty pointer" { var x: u16 = 0; var y: *u8 = @ptrFromInt(x); _ = y; } ``` ``` Test [23/126] test.naughty pointer... thread 21598 panic: cast causes pointer to be null ./test-c1.zig:252:18: 0x260a91 in test.naughty pointer (test) var y: *u8 = @ptrFromInt(x); ^ ``` Zig also has const pointers, which cannot be used to modify the referenced data. Referencing a const variable will yield a const pointer. <!--fail_test--> ```zig test "const pointers" { const x: u8 = 1; var y = &x; y.* += 1; } ``` ``` error: cannot assign to constant y.* += 1; ^ ``` A `*T` coerces to a `*const T`.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/08.error-try.zig
// hide-start const expect = @import("std").testing.expect; fn failingFunction() error{Oops}!void { return error.Oops; } //hide-end fn failFn() error{Oops}!i32 { try failingFunction(); return 12; } test "try" { var v = failFn() catch |err| { try expect(err == error.Oops); return; }; try expect(v == 12); // is never reached }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/01.undefined.zig
const a: i32 = undefined; var b: u32 = undefined;
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/15-enums.mdx
import CodeBlock from "@theme/CodeBlock"; import EnumOrdinal from "!!raw-loader!./15.enum-ordinal.zig"; import EnumOrdinalOverride from "!!raw-loader!./15.enum-ordinal-override.zig"; import EnumMethods from "!!raw-loader!./15.enum-methods.zig"; import EnumDeclarations from "!!raw-loader!./15.enum-declarations.zig"; # Enums Zig's enums allow you to define types with a restricted set of named values. Let's declare an enum. ```zig const Direction = enum { north, south, east, west }; ``` Enums types may have specified (integer) tag types. ```zig const Value = enum(u2) { zero, one, two }; ``` Enum's ordinal values start at 0. They can be accessed with the built-in function [`@intFromEnum`](https://ziglang.org/documentation/master/#intFromEnum). <CodeBlock language="zig">{EnumOrdinal}</CodeBlock> Values can be overridden, with the next values continuing from there. <CodeBlock language="zig">{EnumOrdinalOverride}</CodeBlock> Enums can be given methods. These act as namespaced functions that can be called with the dot syntax. <CodeBlock language="zig">{EnumMethods}</CodeBlock> Enums can also be given `var` and `const` declarations. These act as namespaced globals, and their values are unrelated and unattached to instances of the enum type. <CodeBlock language="zig">{EnumDeclarations}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/01-language-basics/25-payload-captures.md
# Payload Captures Payload captures use the syntax `|value|` and appear in many places, some of which we've seen already. Wherever they appear, they are used to "capture" the value from something. With if statements and optionals. ```zig test "optional-if" { var maybe_num: ?usize = 10; if (maybe_num) |n| { try expect(@TypeOf(n) == usize); try expect(n == 10); } else { unreachable; } } ``` With if statements and error unions. The else with the error capture is required here. ```zig test "error union if" { var ent_num: error{UnknownEntity}!u32 = 5; if (ent_num) |entity| { try expect(@TypeOf(entity) == u32); try expect(entity == 5); } else |err| { _ = err catch {}; unreachable; } } ``` With while loops and optionals. This may have an else block. ```zig test "while optional" { var i: ?u32 = 10; while (i) |num| : (i.? -= 1) { try expect(@TypeOf(num) == u32); if (num == 1) { i = null; break; } } try expect(i == null); } ``` With while loops and error unions. The else with the error capture is required here. ```zig var numbers_left2: u32 = undefined; fn eventuallyErrorSequence() !u32 { return if (numbers_left2 == 0) error.ReachedZero else blk: { numbers_left2 -= 1; break :blk numbers_left2; }; } test "while error union capture" { var sum: u32 = 0; numbers_left2 = 3; while (eventuallyErrorSequence()) |value| { sum += value; } else |err| { try expect(err == error.ReachedZero); } } ``` For loops. ```zig test "for capture" { const x = [_]i8{ 1, 5, 120, -5 }; for (x) |v| try expect(@TypeOf(v) == i8); } ``` Switch cases on tagged unions. ```zig const Info = union(enum) { a: u32, b: []const u8, c, d: u32, }; test "switch capture" { var b = Info{ .a = 10 }; const x = switch (b) { .b => |str| blk: { try expect(@TypeOf(str) == []const u8); break :blk 1; }, .c => 2, //if these are of the same type, they //may be inside the same capture group .a, .d => |num| blk: { try expect(@TypeOf(num) == u32); break :blk num * 2; }, }; try expect(x == 20); } ``` As we saw in the Union and Optional sections above, values captured with the `|val|` syntax are immutable (similar to function arguments), but we can use pointer capture to modify the original values. This captures the values as pointers that are themselves still immutable, but because the value is now a pointer, we can modify the original value by dereferencing it: ```zig test "for with pointer capture" { var data = [_]u8{ 1, 2, 3 }; for (&data) |*byte| byte.* += 1; try expect(eql(u8, &data, &[_]u8{ 2, 3, 4 })); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/_category_.json
{ "label": "Build System", "link": { "description": "Getting started with the Zig programming language." } }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/05-builder.md
# Builder Zig's [`std.Build`](https://ziglang.org/documentation/master/std/#std.Build) type contains the information used by the build runner. This includes information such as: - the build target - the release mode - locations of libraries - the install path - build steps
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/08-build-steps.md
# Build steps Build steps are a way of providing tasks for the build runner to execute. Let's create a build step, and make it the default. When you run `zig build` this will output `Hello!`. <!--no_test--> ```zig const std = @import("std"); pub fn build(b: *std.build.Builder) void { const step = b.step("task", "do something"); step.makeFn = myTask; b.default_step = step; } fn myTask(self: *std.build.Step, progress: *std.Progress.Node) !void { std.debug.print("Hello!\n", .{}); _ = progress; _ = self; } ``` We called `b.installArtifact(exe)` earlier - this adds a build step which tells the builder to build the executable.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/04-zig-build.md
# Zig Build The `zig build` command allows users to compile based on a `build.zig` file. `zig init-exe` and `zig init-lib` can be used to give you a baseline project. Let's use `zig init-exe` inside a new folder. This is what you will find. ``` . β”œβ”€β”€ build.zig └── src └── main.zig ``` `build.zig` contains our build script. The _build runner_ will use this `pub fn build` function as its entry point - this is what is executed when you run `zig build`. <!--no_test--> ```zig const std = @import("std"); // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external // runner. pub fn build(b: *std.Build) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard optimization options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "tmp", // In this case the main source file is merely a path, however, in more // complicated build scripts, this could be a generated file. .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default // step when running `zig build`). b.installArtifact(exe); // This *creates* a Run step in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); // By making the run step depend on the install step, it will be run from the // installation directory rather than directly from within the cache directory. // This is not necessary, however, if the application depends on other installed // files, this ensures they will be present and in the expected location. run_cmd.step.dependOn(b.getInstallStep()); // This allows the user to pass arguments to the application in the build // command itself, like this: `zig build run -- arg1 arg2 etc` if (b.args) |args| { run_cmd.addArgs(args); } // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build run` // This will evaluate the `run` step rather than the default, which is "install". const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Creates a step for unit testing. This only builds the test executable // but does not run it. const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); // Similar to creating the run step earlier, this exposes a `test` step to // the `zig build --help` menu, providing a way for the user to request // running the unit tests. const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); } ``` `main.zig` contains our executable's entry point. <!--no_test--> ```zig const std = @import("std"); pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); // stdout is for the actual output of your application, for example if you // are implementing gzip, then only the compressed bytes should be sent to // stdout, not any debugging messages. const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); try stdout.print("Run `zig build test` to run the tests.\n", .{}); try bw.flush(); // don't forget to flush! } test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator); defer list.deinit(); // try commenting this out and see if zig detects the memory leak! try list.append(42); try std.testing.expectEqual(@as(i32, 42), list.pop()); } ``` Upon using the `zig build` command, the executable will appear in the install path. Here we have not specified an install path, so the executable will be saved in `./zig-out/bin`. A custom install path can be specified using the `override_dest_dir` field in the `Step.Compile` struct.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/03-cross-compilation.md
# Cross compilation By default, Zig will compile for your combination of CPU and OS. This can be overridden by `-target`. Let's compile our tiny hello world to a 64 bit arm linux platform. `zig build-exe .\tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded -target aarch64-linux` [QEMU](https://www.qemu.org/) or similar may be used to conveniently test executables made for foreign platforms. Some CPU architectures that you can cross-compile for: - `x86_64` - `arm` - `aarch64` - `i386` - `riscv64` - `wasm32` Some operating systems you can cross-compile for: - `linux` - `macos` - `windows` - `freebsd` - `netbsd` - `dragonfly` - `UEFI` Many other targets are available for compilation, but aren't as well tested as of now. See [Zig's support table](https://ziglang.org/learn/overview/#wide-range-of-targets-supported) for more information; the list of well tested targets is slowly expanding. As Zig compiles for your specific CPU by default, these binaries may not run on other computers with slightly different CPU architectures. It may be useful to instead specify a specific baseline CPU model for greater compatibility. Note: choosing an older CPU architecture will bring greater compatibility, but means you also miss out on newer CPU instructions; there is an efficiency/speed versus compatibility trade-off here. Let's compile a binary for a sandybridge CPU (Intel x86_64, circa 2011), so we can be reasonably sure that someone with an x86_64 CPU can run our binary. Here we can use `native` in place of our CPU or OS, to use our system's. `zig build-exe .\tiny-hello.zig -target x86_64-native -mcpu sandybridge` Details on what architectures, OSes, CPUs and ABIs (details on ABIs in the next chapter) are available can be found by running `zig targets`. Note: the output is long, and you may want to pipe it to a file, e.g. `zig targets > targets.json`.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/02-emitting-an-executable.md
# Emitting an Executable The commands `zig build-exe`, `zig build-lib`, and `zig build-obj` can be used to output executables, libraries and objects, respectively. These commands take in a source file and arguments. Some common arguments: - `-fsingle-threaded`, which asserts the binary is single-threaded. This will turn thread safety measures such as mutexes into no-ops. - `-fstrip`, which removes debug info from the binary. - `--dynamic`, which is used in conjunction with `zig build-lib` to output a dynamic/shared library. Let's create a tiny hello world. Save this as `tiny-hello.zig`, and run `zig build-exe .\tiny-hello.zig -O ReleaseSmall -fstrip -fsingle-threaded`. Currently for `x86_64-windows`, this produces a 2.5KiB executable. <!--no_test--> ```zig const std = @import("std"); pub fn main() void { std.io.getStdOut().writeAll( "Hello World!", ) catch unreachable; } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/01-build-modes.md
--- pagination_prev: standard-library/advanced-formatting --- # Build Modes Zig provides four build modes, with debug being the default as it produces the shortest compile times. | | Runtime Safety | Optimizations | | ------------ | -------------- | ------------- | | Debug | Yes | No | | ReleaseSafe | Yes | Yes, Speed | | ReleaseSmall | No | Yes, Size | | ReleaseFast | No | Yes, Speed | These may be enabled in `zig run` and `zig test` with the arguments `-O ReleaseSafe`, `-O ReleaseSmall` and `-O ReleaseFast`. Users are recommended to develop their software with runtime safety enabled, despite its small speed disadvantage.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/07-modules.md
# Modules The Zig build system has the concept of modules, which are other source files written in Zig. Let's make use of a module. From a new folder, run the following commands. ``` zig init-exe mkdir libs cd libs git clone https://github.com/Sobeston/table-helper.git ``` Your directory structure should be as follows. ``` . β”œβ”€β”€ build.zig β”œβ”€β”€ libs β”‚ └── table-helper β”‚ β”œβ”€β”€ example-test.zig β”‚ β”œβ”€β”€ README.md β”‚ β”œβ”€β”€ table-helper.zig β”‚ └── zig.mod └── src └── main.zig ``` To your newly made `build.zig`, add the following lines. <!--no_test--> ```zig const table_helper = b.addModule("table-helper", .{ .root_source_file = .{ .path = "libs/table-helper/table-helper.zig" } }); exe.root_module.addImport("table-helper", table_helper); ``` Now when run via `zig build`, [`@import`](https://ziglang.org/documentation/master/#import) inside your `main.zig` will work with the string "table-helper". This means that main has the table-helper package. Packages (type [`std.build.Pkg`](https://ziglang.org/documentation/master/std/#std;build.Pkg)) also have a field for dependencies of type `?[]const Pkg`, which is defaulted to null. This allows you to have packages which rely on other packages. Place the following inside your `main.zig` and run `zig build run`. <!--no_test--> ```zig const std = @import("std"); const Table = @import("table-helper").Table; pub fn main() !void { try std.io.getStdOut().writer().print("{}\n", .{ Table(&[_][]const u8{ "Version", "Date" }){ .data = &[_][2][]const u8{ .{ "0.7.1", "2020-12-13" }, .{ "0.7.0", "2020-11-08" }, .{ "0.6.0", "2020-04-13" }, .{ "0.5.0", "2019-09-30" }, }, }, }); } ``` This should print this table to your console. ``` Version Date ------- ---------- 0.7.1 2020-12-13 0.7.0 2020-11-08 0.6.0 2020-04-13 0.5.0 2019-09-30 ``` Zig does not yet have an official package manager. Some unofficial experimental package managers however do exist, namely [`zigmod`](https://github.com/nektro/zigmod). The `table-helper` package is designed to support it. Some good places to find packages include: [astrolabe.pm](https://astrolabe.pm), [zpm](https://zpm.random-projects.net/), [awesome-zig](https://github.com/nrdmn/awesome-zig/), and the [zig tag on GitHub](https://github.com/topics/zig).
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/06-compilestep.md
# CompileStep The `std.build.CompileStep` type contains information required to build a library, executable, object, or test. Let's make use of our `Builder` and create a `CompileStep` using `Builder.addExecutable`, which takes in a name and a path to the root of the source. <!--no_test--> ```zig const Builder = @import("std").build.Builder; pub fn build(b: *Builder) void { const exe = b.addExecutable(.{ .name = "init-exe", .root_source_file = .{ .path = "src/main.zig" }, }); b.installArtifact(exe); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/03-build-system/09-generating-documentation.md
--- pagination_next: working-with-c/abi --- # Generating Documentation The Zig compiler comes with automatic documentation generation. This can be invoked by adding `-femit-docs` to your `zig build-{exe, lib, obj}` or `zig run` command. This documentation is saved into `./docs`, as a small static website. Zig's documentation generation makes use of _doc comments_ which are similar to comments, using `///` instead of `//`, and preceding globals. Here we will save this as `x.zig` and build documentation for it with `zig build-lib -femit-docs x.zig -target native-windows`. There are some things to take away here: - Only things that are public with a doc comment will appear - Blank doc comments may be used - Doc comments can make use of subset of markdown - Things will only appear inside generated documentation if the compiler analyses them; you may need to force analysis to happen to get things to appear. <!--no_test--> ```zig const std = @import("std"); const w = std.os.windows; ///**Opens a process**, giving you a handle to it. ///[MSDN](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess) pub extern "kernel32" fn OpenProcess( ///[The desired process access rights](https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights) dwDesiredAccess: w.DWORD, /// bInheritHandle: w.BOOL, dwProcessId: w.DWORD, ) callconv(w.WINAPI) ?w.HANDLE; ///spreadsheet position pub const Pos = struct{ ///row x: u32, ///column y: u32, }; pub const message = "hello!"; //used to force analysis, as these things aren't otherwise referenced. comptime { _ = OpenProcess; _ = Pos; _ = message; } //Alternate method to force analysis of everything automatically, but only in a test build: test "Force analysis" { comptime { std.testing.refAllDecls(@This()); } } ``` When using a `build.zig` this may be invoked by setting the `emit_docs` field to `.emit` on a `CompileStep`. We can create a build step to generate docs as follows and invoke it with `$ zig build docs`. <!--no_test--> ```zig const std = @import("std"); pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); const lib = b.addStaticLibrary("x", "src/x.zig"); lib.setBuildMode(mode); lib.install(); const tests = b.addTest("src/x.zig"); tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&tests.step); //Build step to generate docs: const docs = b.addTest("src/x.zig"); docs.setBuildMode(mode); docs.emit_docs = .emit; const docs_step = b.step("docs", "Generate docs"); docs_step.dependOn(&docs.step); } ``` This generation is experimental, and often fails with complex examples. This is used by the [standard library documentation](https://ziglang.org/documentation/master/std/). When merging error sets, the left-most error set's documentation strings take priority over the right. In this case, the doc comment for `C.PathNotFound` is the doc comment provided in `A`. <!--no_test--> ```zig const A = error{ NotDir, /// A doc comment PathNotFound, }; const B = error{ OutOfMemory, /// B doc comment PathNotFound, }; const C = A || B; ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/02-c-primitive-types.md
# C Primitive Types Zig provides special `c_` prefixed types for conforming to the C ABI. These do not have fixed sizes but rather change in size depending on the ABI being used. | Type | C Equivalent | Minimum Size (bits) | | ------------ | ------------------ | ------------------- | | c_short | short | 16 | | c_ushort | unsigned short | 16 | | c_int | int | 16 | | c_uint | unsigned int | 16 | | c_long | long | 32 | | c_ulong | unsigned long | 32 | | c_longlong | long long | 64 | | c_ulonglong | unsigned long long | 64 | | c_longdouble | long double | N/A | | anyopaque | void | N/A | Note: C's void (and Zig's `anyopaque`) has an unknown non-zero size. Zig's `void` is a true zero-sized type.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/03-calling-conventions.md
# Calling conventions Calling conventions describe how functions are called. This includes how arguments are supplied to the function (i.e. where they go - in registers or on the stack, and how), and how the return value is received. In Zig, the attribute `callconv` may be given to a function. The calling conventions available may be found in [std.builtin.CallingConvention](https://ziglang.org/documentation/master/std/#std.builtin.CallingConvention). Here we make use of the cdecl calling convention. ```zig fn add(a: u32, b: u32) callconv(.C) u32 { return a + b; } ``` Marking your functions with the C calling convention is crucial when you're calling Zig from C.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/06-packed-structs.md
# Packed Structs By default, all struct fields in Zig are naturally aligned to that of [`@alignOf(FieldType)`](https://ziglang.org/documentation/master/#alignOf) (the ABI size), but without a defined layout. Sometimes you may want to have struct fields with a defined layout that do not conform to your C ABI. `packed` structs allow you to have extremely precise control of your struct fields, allowing you to place your fields on a bit-by-bit basis. Inside packed structs, Zig's integers take their bit-width in space (i.e. a `u12` has an [`@bitSizeOf`](https://ziglang.org/documentation/master/#bitSizeOf) of 12, meaning it will take up 12 bits in the packed struct). Bools also take up 1 bit, meaning you can implement bit flags easily. ```zig const MovementState = packed struct { running: bool, crouching: bool, jumping: bool, in_air: bool, }; test "packed struct size" { try expect(@sizeOf(MovementState) == 1); try expect(@bitSizeOf(MovementState) == 4); const state = MovementState{ .running = true, .crouching = true, .jumping = true, .in_air = true, }; _ = state; } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/12-zig-cc.md
--- pagination_next: async/introduction --- # Zig cc, Zig c++ The Zig executable comes with Clang embedded inside it alongside libraries and headers required to cross-compile for other operating systems and architectures. This means that not only can `zig cc` and `zig c++` compile C and C++ code (with Clang-compatible arguments), but it can also do so while respecting Zig's target triple argument; the single Zig binary that you have installed has the power to compile for several different targets without the need to install multiple versions of the compiler or any addons. Using `zig cc` and `zig c++` also makes use of Zig's caching system to speed up your workflow. Using Zig, one can easily construct a cross-compiling toolchain for languages which make use of a C and/or C++ compiler. Some examples in the wild: - [Using zig cc to cross compile LuaJIT to aarch64-linux from x86_64-linux](https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html) - [Using zig cc and zig c++ in combination with cgo to cross compile hugo from aarch64-macos to x86_64-linux, with full static linking](https://twitter.com/croloris/status/1349861344330330114)
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/_category_.json
{ "label": "Working with C", "link": { "description": "Zig has been designed from the ground up with C interop as a first-class feature. In this section, we will go over how this works." } }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/08-c-pointers.md
# C Pointers Up until now, we have used the following kinds of pointers: - single item pointers - `*T` - many item pointers - `[*]T` - slices - `[]T` Unlike the aforementioned pointers, C pointers cannot deal with specially aligned data and may point to the address `0`. C pointers coerce back and forth between integers, and also coerce to single and multi item pointers. When a C pointer of value `0` is coerced to a non-optional pointer, this is detectable illegal behaviour. Outside of automatically translated C code, the usage of `[*c]` is almost always a bad idea, and should almost never be used.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/04-extern-structs.md
# Extern Structs Normal structs in Zig do not have a defined layout; `extern` structs are required for when you want the layout of your struct to match the layout of your C ABI. Let's create an extern struct. This test should be run with `x86_64` with a `gnu` ABI, which can be done with `-target x86_64-native-gnu`. ```zig const expect = @import("std").testing.expect; const Data = extern struct { a: i32, b: u8, c: f32, d: bool, e: bool }; test "hmm" { const x = Data{ .a = 10005, .b = 42, .c = -10.5, .d = false, .e = true, }; const z = @as([*]const u8, @ptrCast(&x)); try expect(@as(*const i32, @ptrCast(@alignCast(z))).* == 10005); try expect(@as(*const u8, @ptrCast(@alignCast(z + 4))).* == 42); try expect(@as(*const f32, @ptrCast(@alignCast(z + 8))).* == -10.5); try expect(@as(*const bool, @ptrCast(@alignCast(z + 12))).* == false); try expect(@as(*const bool, @ptrCast(@alignCast(z + 13))).* == true); } ``` This is what the memory inside our `x` value looks like. | Field | a | a | a | a | b | | | | c | c | c | c | d | e | | | | ----- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | | Bytes | 15 | 27 | 00 | 00 | 2A | 00 | 00 | 00 | 00 | 00 | 28 | C1 | 00 | 01 | 00 | 00 | Note how there are gaps in the middle and at the end - this is called "padding". The data in this padding is undefined memory, and won't always be zero. As our `x` value is that of an extern struct, we could safely pass it into a C function expecting a `Data`, providing the C function was also compiled with the same `gnu` ABI and CPU arch.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/10-c-import.md
# cImport Zig's [`@cImport`](https://ziglang.org/documentation/master/#cImport) builtin is unique in that it takes in an expression, which can only take in [`@cInclude`](https://ziglang.org/documentation/master/#cInclude), [`@cDefine`](https://ziglang.org/documentation/master/#cDefine), and [`@cUndef`](https://ziglang.org/documentation/master/#cUndef). This works similarly to translate-c, translating C code to Zig under the hood. [`@cInclude`](https://ziglang.org/documentation/master/#cInclude) takes in a path string and adds the path to the includes list. [`@cDefine`](https://ziglang.org/documentation/master/#cDefine) and [`@cUndef`](https://ziglang.org/documentation/master/#cUndef) define and undefine things for the import. These three functions work exactly as you'd expect them to work within C code. Similar to [`@import`](https://ziglang.org/documentation/master/#import), this returns a struct type with declarations. It is typically recommended to only use one instance of [`@cImport`](https://ziglang.org/documentation/master/#cImport) in an application to avoid symbol collisions; the types generated within one cImport will not be equivalent to those generated in another. cImport is only available when linking libc.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/07-bit-aligned-pointers.md
# Bit Aligned Pointers Similar to aligned pointers, bit-aligned pointers have extra information in their type, which informs how to access the data. These are necessary when the data is not byte-aligned. Bit alignment information is often needed to address fields inside of packed structs. ```zig test "bit aligned pointers" { var x = MovementState{ .running = false, .crouching = false, .jumping = false, .in_air = false, }; const running = &x.running; running.* = true; const crouching = &x.crouching; crouching.* = true; try expect(@TypeOf(running) == *align(1:0:1) bool); try expect(@TypeOf(crouching) == *align(1:1:1) bool); try expect(@import("std").meta.eql(x, .{ .running = true, .crouching = true, .jumping = false, .in_air = false, })); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/05-alignment.md
# Alignment For circuitry reasons, CPUs access primitive values at specific multiples in memory. This could mean, for example, that the address of an `f32` value must be a multiple of 4, meaning `f32` has an alignment of 4. This so-called "natural alignment" of primitive data types depends on CPU architecture. All alignments are powers of 2. Data of a larger alignment also has the alignment of every smaller alignment; for example, a value which has an alignment of 16 also has an alignment of 8, 4, 2 and 1. We can make specially aligned data by using the `align(x)` property. Here we are making data with a greater alignment. ```zig const a1: u8 align(8) = 100; const a2 align(8) = @as(u8, 100); ``` And making data with a lesser alignment. Note: Creating data of a lesser alignment isn't particularly useful. ```zig const b1: u64 align(1) = 100; const b2 align(1) = @as(u64, 100); ``` Like `const`, `align` is also a property of pointers. ```zig test "aligned pointers" { const a: u32 align(8) = 5; try expect(@TypeOf(&a) == *align(8) const u32); } ``` Let's make use of a function expecting an aligned pointer. ```zig fn total(a: *align(64) const [64]u8) u32 { var sum: u32 = 0; for (a) |elem| sum += elem; return sum; } test "passing aligned data" { const x align(64) = [_]u8{10} ** 64; try expect(total(&x) == 640); } ```
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/11-linking-libc.md
# Linking libc Linking libc can be done via the command line via `-lc`, or via `build.zig` using `exe.linkLibC();`. The libc used is that of the compilation's target; Zig provides libc for many targets.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/01-abi.md
--- pagination_prev: build-system/generating-documentation --- # ABI An ABI _(application binary interface)_ is a standard, pertaining to: - The in-memory layout of types (i.e. a type's size, alignment, offsets, and the layouts of its fields) - The in-linker naming of symbols (e.g. name mangling) - The calling conventions of functions (i.e. how a function call works at a binary level) By defining these rules and not breaking them, an ABI is said to be stable, and this can be used to, for example, reliably link together multiple libraries, executables, or objects which were compiled separately (potentially on different machines or using different compilers). This allows for FFI _(foreign function interface)_ to take place, where we can share code between programming languages. Zig natively supports C ABIs for `extern` things; which C ABI is used depends on the target you are compiling for (e.g. CPU architecture, operating system). This allows for near-seamless interoperation with code that was not written in Zig; the usage of C ABIs is standard amongst programming languages. Zig internally does not use an ABI, meaning code should explicitly conform to a C ABI where reproducible and defined binary-level behaviour is needed.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/04-working-with-c/09-translate-c.md
# Translate-C Zig provides the command `zig translate-c` for automatic translation from C source code. Create the file `main.c` with the following contents. ```c #include <stddef.h> void int_sort(int* array, size_t count) { for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - i - 1; j++) { if (array[j] > array[j+1]) { int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } } } ``` Run the command `zig translate-c main.c` to get the equivalent Zig code output to your console (stdout). You may wish to pipe this into a file with `zig translate-c main.c > int_sort.zig` (warning for Windows users: piping in PowerShell will produce a file with the incorrect encoding - use your editor to correct this). In another file you could use `@import("int_sort.zig")` to use this function. Currently the code produced may be unnecessarily verbose, though translate-c successfully translates most C code into Zig. You may wish to use translate-c to produce Zig code before editing it into more idiomatic code; a gradual transfer from C to Zig within a codebase is a supported use case.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/04.running-tests-success.zig
const std = @import("std"); const expect = std.testing.expect; test "always succeeds" { try expect(true); }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/01-welcome.mdx
--- slug: / description: Get started with the Zig programming language. Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software. pagination_prev: null --- # Welcome [Zig](https://ziglang.org) is a general-purpose programming language and toolchain for maintaining **robust**, **optimal**, and **reusable** software. :::warning The latest release of Zig is 0.11.0 and is currently unstable. ::: To follow this guide, we assume you have: - Prior experience programming - Some understanding of low-level programming concepts Knowing a language like C, C++, Rust, Go, Pascal or similar will help you follow this guide. You must have an editor, terminal and internet connection available to you.
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/_category_.json
{ "label": "Getting Started", "link": { "description": "zig.guide - A Guide & Tutorial for the Zig programming language. Install and get started with ziglang here." } }
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/02-installation.mdx
--- description: Installation instructions for the Zig programming language on Linux, Windows, and macOS. --- import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; # Installation <Tabs defaultValue="linux" values={[ {label: 'Linux', value: 'linux'}, {label: 'Windows', value: 'windows'}, {label: 'macOS', value: 'macos'}, ]}> <TabItem value="linux"> Consider getting Zig from your distribution's [package manager](https://github.com/ziglang/zig/wiki/Install-Zig-from-a-Package-Manager). Most major linux distros package the latest Zig release. ### Installing manually 1. [Download](https://ziglang.org/download/#release-0.11.0) a prebuilt version of Zig. Choose a build of Zig 0.11 for linux that matches your CPU architecture. If you're unsure which architecture you're using, this can be found with: ```bash uname -m ``` 2. Extract the archive using tar, e.g. ```bash tar xf zig-linux-x86_64-0.11.0.tar.xz ``` 3. Add the location of your Zig binary to your path, e.g. ```bash echo 'export PATH="$HOME/zig-linux-x86_64-0.11.0:$PATH"' >> ~/.bashrc ``` </TabItem> <TabItem value="windows"> Consider getting Zig from a package manager such as [chocolatey](https://chocolatey.org/), [scoop](https://scoop.sh/), or [winget](https://learn.microsoft.com/en-us/windows/package-manager/winget/#install-winget). All commands shown are to be used inside powershell. ```powershell choco install zig ``` ``` winget install zig.zig ``` ``` scoop install zig ``` ### Installing manually 1. [Download](https://ziglang.org/download/#release-0.11.0) a prebuilt version of Zig. Choose a build of Zig 0.11 for windows that matches your CPU architecture. Most Windows systems use `x86_64`, also known as `AMD64`. If you're unsure which architecture you're using, this can be found with: ```powershell $Env:PROCESSOR_ARCHITECTURE ``` 2. Extract Zig. 3. Add Zig to your path: <Tabs defaultValue="user" values={[ {label: 'Current User', value: 'user'}, {label: 'System Wide', value: 'system'}, ]}> <TabItem value="user"> ```powershell [Environment]::SetEnvironmentVariable( "Path", [Environment]::GetEnvironmentVariable("Path", "User") + ";C:\_\zig-windows-_", "User" ) ``` </TabItem> <TabItem value="system"> ```powershell [Environment]::SetEnvironmentVariable( "Path", [Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\_\zig-windows-_", "Machine" ) ``` </TabItem> </Tabs> Close your terminal and create a new one. </TabItem> <TabItem value="macos"> Consider getting Zig from a package manager such as [brew](https://brew.sh/). ``` brew install zig ``` </TabItem> </Tabs> ### Verifying your install Verify your installation with `zig version`. The output should look like this: ``` $ zig version 0.11.0 ``` ### Extras For completions and go-to-definition in your editor, consider installing the [Zig Language Server](https://github.com/zigtools/zls/#installation). Consider joining a [Zig community](https://github.com/ziglang/zig/wiki/Community).
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/03-hello-world.mdx
--- description: Write your first program using the Zig programming language. --- # Hello World Create a file called `main.zig`, with the following contents: ```zig const std = @import("std"); pub fn main() void { std.debug.print("Hello, {s}!\n", .{"World"}); } ``` Use `zig run main.zig` to build and run it. In this example, `Hello, World!` will be written to stderr, and is assumed to never fail. :::warning found 'invalid bytes' Make sure your `main.zig` file is UTF-8 encoded as the Zig compiler does not currently support other encodings. To re-encode your file as UTF-8, run `zig fmt main.zig` and reopen the file in your editor. :::
0
repos/zig.guide/website/versioned_docs/version-0.11
repos/zig.guide/website/versioned_docs/version-0.11/00-getting-started/04-running-tests.mdx
--- pagination_next: language-basics/assignment --- import CodeBlock from "@theme/CodeBlock"; import Success from "!!raw-loader!./04.running-tests-success.zig"; # Running Tests In this guide, code examples are often given as runnable tests. Before proceeding, make sure that you can run them successfully. ### Success Save the following text as `test_pass.zig`, and run `zig test test_pass.zig`; you should read `All 1 tests passed.` in your terminal. <CodeBlock language="zig">{Success}</CodeBlock> :::note Some code examples in this guide will have their imports at the top hidden, make sure to get them by clicking the copy button on the top-right of the code block. ::: ### Failure Now, save the following text as `test_fail.zig` and observe it fail. ```zig const std = @import("std"); const expect = std.testing.expect; test "always fails" { try expect(false); } ``` Which should output something like: ``` Test [1/1] test.always fails... FAIL (TestUnexpectedResult) /usr/lib/zig/std/testing.zig:515:14: 0x2241ef in expect (test) if (!ok) return error.TestUnexpectedResult; ^ [...]/test_fail:5:5: 0x224305 in test.always fails (test) try expect(false); ^ 0 passed; 0 skipped; 1 failed. ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/_category_.json
{ "label": "Async", "link": { "description": "Details on how Zig's async features work." } }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/02-suspend-resume.md
# Suspend / Resume In the previous section we talked of how async functions can give control back to the caller, and how the async function can later take control back. This functionality is provided by the keywords [`suspend`, and `resume`](https://ziglang.org/documentation/master/#Suspend-and-Resume). When a function suspends, control flow returns to wherever it was last resumed; when a function is called via an `async` invocation, this is an implicit resume. The comments in these examples indicate the order of execution. There are a few things to take in here: - The `async` keyword is used to invoke functions in an async context. - `async func()` returns the function's frame. - We must store this frame. - The `resume` keyword is used on the frame, whereas `suspend` is used from the called function. This example has a suspend, but no matching resume. ```zig const expect = @import("std").testing.expect; var foo: i32 = 1; test "suspend with no resume" { var frame = async func(); //1 _ = frame; try expect(foo == 2); //4 } fn func() void { foo += 1; //2 suspend {} //3 foo += 1; //never reached! } ``` In well formed code, each suspend is matched with a resume. ```zig var bar: i32 = 1; test "suspend with resume" { var frame = async func2(); //1 resume frame; //4 try expect(bar == 3); //6 } fn func2() void { bar += 1; //2 suspend {} //3 bar += 1; //5 } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/03-async-await.md
# Async / Await Similar to how well formed code has a suspend for every resume, each `async` function invocation with a return value must be matched with an `await`. The value yielded by `await` on the async frame corresponds to the function's return. You may notice that `func3` here is a normal function (i.e. it has no suspend points - it is not an async function). Despite this, `func3` can work as an async function when called from an async invocation; the calling convention of `func3` doesn't have to be changed to async - `func3` can be of any calling convention. ```zig fn func3() u32 { return 5; } test "async / await" { var frame = async func3(); try expect(await frame == 5); } ``` Using `await` on an async frame of a function which may suspend is only possible from async functions. As such, functions that use `await` on the frame of an async function are also considered async functions. If you can be sure that the potential suspend doesn't happen, `nosuspend await` will stop this from happening.
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/01-introduction.md
--- pagination_prev: working-with-c/zig-cc --- # Introduction :::danger Zig's async features have not been present in the compiler for multiple major versions. There is currently no estimate on when async will be added back to the compiler; async's future is unclear. The following code will not compile with Zig 0.11 or Zig 0.12. ::: A functioning understanding of Zig's async requires familiarity with the concept of the call stack. If you have not heard of this before, [check out the wikipedia page](https://en.wikipedia.org/wiki/Call_stack). <!-- TODO: actually explain the call stack? --> A traditional function call comprises of three things: 1. Initiate the called function with its arguments, pushing the function's stack frame 2. Transfer control to the function 3. Upon function completion, hand control back to the caller, retrieving the function's return value and popping the function's stack frame With Zig's async functions we can do more than this, with the transfer of control being an ongoing two-way conversation (i.e. we can give control to the function and take it back multiple times). Because of this, special considerations must be made when calling a function in an async context; we can no longer push and pop the stack frame as normal (as the stack is volatile, and things "above" the current stack frame may be overwritten), instead explicitly storing the async function's frame. While most people won't make use of its full feature set, this style of async is useful for creating more powerful constructs such as event loops. The style of Zig's async may be described as suspendible stackless coroutines. Zig's async is very different to something like an OS thread which has a stack, and can only be suspended by the kernel. Furthermore, Zig's async is there to provide you with control flow structures and code generation; async does not imply parallelism or the usage of threads.
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/04-nosuspend.md
# Nosuspend When calling a function which is determined to be async (i.e. it may suspend) without an `async` invocation, the function which called it is also treated as being async. When a function of a concrete (non-async) calling convention is determined to have suspend points, this is a compile error as async requires its own calling convention. This means, for example, that main cannot be async. <!--no_test--> ```zig pub fn main() !void { suspend {} } ``` (compiled from windows) ``` C:\zig\lib\zig\std\start.zig:165:1: error: function with calling convention 'Stdcall' cannot be async fn WinStartup() callconv(.Stdcall) noreturn { ^ C:\zig\lib\zig\std\start.zig:173:65: note: async function call here std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain()); ^ C:\zig\lib\zig\std\start.zig:276:12: note: async function call here return @call(.{ .modifier = .always_inline }, callMain, .{}); ^ C:\zig\lib\zig\std\start.zig:334:37: note: async function call here const result = root.main() catch |err| { ^ .\main.zig:12:5: note: suspends here suspend {} ^ ``` If you want to call an async function without using an `async` invocation, and without the caller of the function also being async, the `nosuspend` keyword comes in handy. This allows the caller of the async function to not also be async, by asserting that the potential suspends do not happen. <!--no_test--> ```zig const std = @import("std"); fn doTicksDuration(ticker: *u32) i64 { const start = std.time.milliTimestamp(); while (ticker.* > 0) { suspend {} ticker.* -= 1; } return std.time.milliTimestamp() - start; } pub fn main() !void { var ticker: u32 = 0; const duration = nosuspend doTicksDuration(&ticker); } ``` In the above code if we change the value of `ticker` to be above 0, this is detectable illegal behaviour. If we run that code, we will have an error like this in safe build modes. Similar to other illegal behaviours in Zig, having these happen in unsafe modes will result in undefined behaviour. ``` async function called in nosuspend scope suspended .\main.zig:16:47: 0x7ff661dd3414 in main (main.obj) const duration = nosuspend doTicksDuration(&ticker); ^ C:\zig\lib\zig\std\start.zig:173:65: 0x7ff661dd18ce in std.start.WinStartup (main.obj) std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain()); ^ ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/06-basic-event-loop.md
# Basic Event Loop Implementation An event loop is a design pattern in which events are dispatched and/or waited upon. This will mean some kind of service or runtime that resumes suspended async frames when conditions are met. This is the most powerful and useful use case of Zig's async. Here we will implement a basic event loop. This one will allow us to submit tasks to be executed in a given amount of time. We will use this to submit pairs of tasks which will print the time since the program's start. Here is an example of the output. ``` [task-pair b] it is now 499 ms since start! [task-pair a] it is now 1000 ms since start! [task-pair b] it is now 1819 ms since start! [task-pair a] it is now 2201 ms since start! ``` Here is the implementation. <!--no_test--> ```zig const std = @import("std"); // used to get monotonic time, as opposed to wall-clock time var timer: ?std.time.Timer = null; fn nanotime() u64 { if (timer == null) { timer = std.time.Timer.start() catch unreachable; } return timer.?.read(); } // holds the frame, and the nanotime of // when the frame should be resumed const Delay = struct { frame: anyframe, expires: u64, }; // suspend the caller, to be resumed later by the event loop fn waitForTime(time_ms: u64) void { suspend timer_queue.add(Delay{ .frame = @frame(), .expires = nanotime() + (time_ms * std.time.ns_per_ms), }) catch unreachable; } fn waitUntilAndPrint( time1: u64, time2: u64, name: []const u8, ) void { const start = nanotime(); // suspend self, to be woken up when time1 has passed waitForTime(time1); std.debug.print( "[{s}] it is now {} ms since start!\n", .{ name, (nanotime() - start) / std.time.ns_per_ms }, ); // suspend self, to be woken up when time2 has passed waitForTime(time2); std.debug.print( "[{s}] it is now {} ms since start!\n", .{ name, (nanotime() - start) / std.time.ns_per_ms }, ); } fn asyncMain() void { // stores the async frames of our tasks var tasks = [_]@Frame(waitUntilAndPrint){ async waitUntilAndPrint(1000, 1200, "task-pair a"), async waitUntilAndPrint(500, 1300, "task-pair b"), }; // |*t| is used, as |t| would be a *const @Frame(...) // which cannot be awaited upon for (tasks) |*t| await t; } // priority queue of tasks // lower .expires => higher priority => to be executed before var timer_queue: std.PriorityQueue(Delay, void, cmp) = undefined; fn cmp(context: void, a: Delay, b: Delay) std.math.Order { _ = context; return std.math.order(a.expires, b.expires); } pub fn main() !void { timer_queue = std.PriorityQueue(Delay, void, cmp).init( std.heap.page_allocator, undefined ); defer timer_queue.deinit(); var main_task = async asyncMain(); // the body of the event loop // pops the task which is to be next executed while (timer_queue.removeOrNull()) |delay| { // wait until it is time to execute next task const now = nanotime(); if (now < delay.expires) { std.time.sleep(delay.expires - now); } // execute next task resume delay.frame; } nosuspend await main_task; } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/05-async/05-frames-suspend.md
# Async Frames, Suspend Blocks `@Frame(function)` returns the frame type of the function. This works for async functions, and functions without a specific calling convention. ```zig fn add(a: i32, b: i32) i64 { return a + b; } test "@Frame" { var frame: @Frame(add) = async add(1, 2); try expect(await frame == 3); } ``` [`@frame()`](https://ziglang.org/documentation/master/#frame) returns a pointer to the frame of the current function. Similar to `suspend` points, if this call is found in a function then it is inferred as being async. All pointers to frames coerce to the special type `anyframe`, which you can use `resume` upon. This allows us to, for example, write a function that resumes itself. ```zig fn double(value: u8) u9 { suspend { resume @frame(); } return value * 2; } test "@frame 1" { var f = async double(1); try expect(nosuspend await f == 2); } ``` Or, more interestingly, we can use it to tell other functions to resume us. Here we're introducing **suspend blocks**. Upon entering a suspend block, the async function is already considered suspended (i.e. it can be resumed). This means that we can have our function resumed by something other than the last resumer. ```zig const std = @import("std"); fn callLater(comptime laterFn: fn () void, ms: u64) void { suspend { wakeupLater(@frame(), ms); } laterFn(); } fn wakeupLater(frame: anyframe, ms: u64) void { std.time.sleep(ms * std.time.ns_per_ms); resume frame; } fn alarm() void { std.debug.print("Time's Up!\n", .{}); } test "@frame 2" { nosuspend callLater(alarm, 1000); } ``` Using the `anyframe` data type can be thought of as a kind of type erasure, in that we are no longer sure of the concrete type of the function or the function frame. This is useful as it still allows us to resume the frame - in a lot of code we will not care about the details and will just want to resume it. This gives us a single concrete type which we can use for our async logic. The natural drawback of `anyframe` is that we have lost type information, and we no longer know what the return type of the function is. This means we cannot await an `anyframe`. Zig's solution to this is the `anyframe->T` types, where the `T` is the return type of the frame. ```zig fn zero(comptime x: anytype) x { return 0; } fn awaiter(x: anyframe->f32) f32 { return nosuspend await x; } test "anyframe->T" { var frame = async zero(f32); try expect(awaiter(&frame) == 0); } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/08-crypto.md
# Crypto [`std.crypto`](https://ziglang.org/documentation/master/std/#std.crypto) includes many cryptographic utilities, including: - AES (Aes128, Aes256) - Diffie-Hellman key exchange (x25519) - Elliptic-curve arithmetic (curve25519, edwards25519, ristretto255) - Crypto secure hashing (blake2, Blake3, Gimli, Md5, sha1, sha2, sha3) - MAC functions (Ghash, Poly1305) - Stream ciphers (ChaCha20IETF, ChaCha20With64BitNonce, XChaCha20IETF, Salsa20, XSalsa20) This list is inexhaustive. For more in-depth information, try [A tour of std.crypto in Zig 0.7.0 - Frank Denis](https://www.youtube.com/watch?v=9t6Y7KoCvyk).
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/05.formatting-array-print.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; // hide-end test "array printing" { const string = try std.fmt.allocPrint( test_allocator, "{any} + {any} = {any}", .{ @as([]const u8, &[_]u8{ 1, 4 }), @as([]const u8, &[_]u8{ 2, 5 }), @as([]const u8, &[_]u8{ 3, 9 }), }, ); defer test_allocator.free(string); try expect(eql( u8, string, "{ 1, 4 } + { 2, 5 } = { 3, 9 }", )); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/05.formatting-print.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; // hide-end test "print" { var list = std.ArrayList(u8).init(test_allocator); defer list.deinit(); try list.writer().print( "{} + {} = {}", .{ 9, 10, 19 }, ); try expect(eql(u8, list.items, "9 + 10 = 19")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/11-stacks.md
# Stacks [`std.ArrayList`](https://ziglang.org/documentation/master/std/#std.ArrayList) provides the methods necessary to use it as a stack. Here's an example of creating a list of matched brackets. ```zig test "stack" { const string = "(()())"; var stack = std.ArrayList(usize).init( test_allocator, ); defer stack.deinit(); const Pair = struct { open: usize, close: usize }; var pairs = std.ArrayList(Pair).init( test_allocator, ); defer pairs.deinit(); for (string, 0..) |char, i| { if (char == '(') try stack.append(i); if (char == ')') try pairs.append(.{ .open = stack.pop(), .close = i, }); } for (pairs.items, 0..) |pair, i| { try expect(std.meta.eql(pair, switch (i) { 0 => Pair{ .open = 1, .close = 2 }, 1 => Pair{ .open = 3, .close = 4 }, 2 => Pair{ .open = 0, .close = 5 }, else => unreachable, })); } } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/03-filesystem.mdx
import CodeBlock from "@theme/CodeBlock"; import CwdCreate from "!!raw-loader!./03.filesystem-cwd-create.zig"; import Stat from "!!raw-loader!./03.filesystem-stat.zig"; import MakeDirIterable from "!!raw-loader!./03.filesystem-make-dir-iterable.zig"; # Filesystem Let's create and open a file in our current working directory, write to it, and then read from it. Here we have to use `.seekTo` to go back to the start of the file before reading what we have written. <CodeBlock language="zig">{CwdCreate}</CodeBlock> The functions [`std.fs.openFileAbsolute`](https://ziglang.org/documentation/master/std/#std.fs.openFileAbsolute) and similar absolute functions exist, but we will not test them here. We can get various information about files by using `.stat()` on them. `Stat` also contains fields for .inode and .mode, but they are not tested here as they rely on the current OS' types. When the Enum type is known from context, it can be omitted, so we can compare `stat.kind` to `.file` instead of `Kind.file`. <CodeBlock language="zig">{Stat}</CodeBlock> We can make directories and iterate over their contents. Here we will use an iterator (discussed later). This directory (and its contents) will be deleted after this test finishes. <CodeBlock language="zig">{MakeDirIterable}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/_category_.json
{ "label": "Standard Library", "link": { "description": "Zig's standard library in detail." } }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/04.readers-and-writers-reader.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; // hide-end test "io reader usage" { const message = "Hello File!"; const file = try std.fs.cwd().createFile( "junk_file2.txt", .{ .read = true }, ); defer file.close(); try file.writeAll(message); try file.seekTo(0); const contents = try file.reader().readAllAlloc( test_allocator, message.len, ); defer test_allocator.free(contents); try expect(eql(u8, contents, message)); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/10-hashmaps.md
# Hash Maps The standard library provides [`std.AutoHashMap`](https://ziglang.org/documentation/master/std/#std.AutoHashMap), which lets you easily create a hash map type from a key type and a value type. These must be initiated with an allocator. Let's put some values in a hash map. ```zig test "hashing" { const Point = struct { x: i32, y: i32 }; var map = std.AutoHashMap(u32, Point).init( test_allocator, ); defer map.deinit(); try map.put(1525, .{ .x = 1, .y = -4 }); try map.put(1550, .{ .x = 2, .y = -3 }); try map.put(1575, .{ .x = 3, .y = -2 }); try map.put(1600, .{ .x = 4, .y = -1 }); try expect(map.count() == 4); var sum = Point{ .x = 0, .y = 0 }; var iterator = map.iterator(); while (iterator.next()) |entry| { sum.x += entry.value_ptr.x; sum.y += entry.value_ptr.y; } try expect(sum.x == 10); try expect(sum.y == -10); } ``` `.fetchPut` puts a value in the hash map, returning a value if there was previously a value for that key. ```zig test "fetchPut" { var map = std.AutoHashMap(u8, f32).init( test_allocator, ); defer map.deinit(); try map.put(255, 10); const old = try map.fetchPut(255, 100); try expect(old.?.value == 10); try expect(map.get(255).? == 100); } ``` [`std.StringHashMap`](https://ziglang.org/documentation/master/std/#std.StringHashMap) is also provided for when you need strings as keys. ```zig test "string hashmap" { var map = std.StringHashMap(enum { cool, uncool }).init( test_allocator, ); defer map.deinit(); try map.put("loris", .uncool); try map.put("me", .cool); try expect(map.get("me").? == .cool); try expect(map.get("loris").? == .uncool); } ``` [`std.StringHashMap`](https://ziglang.org/documentation/master/std/#std.StringHashMap) and [`std.AutoHashMap`](https://ziglang.org/documentation/master/std/#std.AutoHashMap) are just wrappers for [`std.HashMap`](https://ziglang.org/documentation/master/std/#std.HashMap). If these two do not fulfil your needs, using [`std.HashMap`](https://ziglang.org/documentation/master/std/#std.HashMap) directly gives you much more control. If having your elements backed by an array is wanted behaviour, try [`std.ArrayHashMap`](https://ziglang.org/documentation/master/std/#std.ArrayHashMap) and its wrapper [`std.AutoArrayHashMap`](https://ziglang.org/documentation/master/std/#std.AutoArrayHashMap).
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/04.readers-and-writers-custom.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end // Don't create a type like this! Use an // arraylist with a fixed buffer allocator const MyByteList = struct { data: [100]u8 = undefined, items: []u8 = &[_]u8{}, const Writer = std.io.Writer( *MyByteList, error{EndOfBuffer}, appendWrite, ); fn appendWrite( self: *MyByteList, data: []const u8, ) error{EndOfBuffer}!usize { if (self.items.len + data.len > self.data.len) { return error.EndOfBuffer; } @memcpy( self.data[self.items.len..][0..data.len], data, ); self.items = self.data[0 .. self.items.len + data.len]; return data.len; } fn writer(self: *MyByteList) Writer { return .{ .context = self }; } }; test "custom writer" { var bytes = MyByteList{}; _ = try bytes.writer().write("Hello"); _ = try bytes.writer().write(" Writer!"); try expect(eql(u8, bytes.items, "Hello Writer!")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01-allocators.mdx
--- pagination_prev: language-basics/imports --- import CodeBlock from "@theme/CodeBlock"; import AllocatorsAlloc from "!!raw-loader!./01.allocators-alloc.zig"; import AllocatorsFba from "!!raw-loader!./01.allocators-fba.zig"; import AllocatorsArena from "!!raw-loader!./01.allocators-arena.zig"; import AllocatorsCreate from "!!raw-loader!./01.allocators-create.zig"; import AllocatorsGpa from "!!raw-loader!./01.allocators-gpa.zig"; # Allocators The Zig standard library provides a pattern for allocating memory, which allows the programmer to choose precisely how memory allocations are done within the standard library - no allocations happen behind your back in the standard library. The most basic allocator is [`std.heap.page_allocator`](https://ziglang.org/documentation/master/std/#std.heap.page_allocator). Whenever this allocator makes an allocation, it will ask your OS for entire pages of memory; an allocation of a single byte will likely reserve multiple kibibytes. As asking the OS for memory requires a system call, this is also extremely inefficient for speed. Here, we allocate 100 bytes as a `[]u8`. Notice how defer is used in conjunction with a free - this is a common pattern for memory management in Zig. <CodeBlock language="zig">{AllocatorsAlloc}</CodeBlock> The [`std.heap.FixedBufferAllocator`](https://ziglang.org/documentation/master/std/#std.heap.FixedBufferAllocator) is an allocator that allocates memory into a fixed buffer and does not make any heap allocations. This is useful when heap usage is not wanted, for example, when writing a kernel. It may also be considered for performance reasons. It will give you the error `OutOfMemory` if it has run out of bytes. <CodeBlock language="zig">{AllocatorsFba}</CodeBlock> [`std.heap.ArenaAllocator`](https://ziglang.org/documentation/master/std/#std.heap.ArenaAllocator) takes in a child allocator and allows you to allocate many times and only free once. Here, `.deinit()` is called on the arena, which frees all memory. Using `allocator.free` in this example would be a no-op (i.e. does nothing). <CodeBlock language="zig">{AllocatorsArena}</CodeBlock> `alloc` and `free` are used for slices. For single items, consider using `create` and `destroy`. <CodeBlock language="zig">{AllocatorsCreate}</CodeBlock> The Zig standard library also has a general-purpose allocator. This is a safe allocator that can prevent double-free, use-after-free and can detect leaks. Safety checks and thread safety can be turned off via its configuration struct (left empty below). Zig's GPA is designed for safety over performance, but may still be many times faster than page_allocator. <CodeBlock language="zig">{AllocatorsGpa}</CodeBlock> For high performance (but very few safety features!), [`std.heap.c_allocator`](https://ziglang.org/documentation/master/std/#std.heap.c_allocator) may be considered. This,however, has the disadvantage of requiring linking Libc, which can be done with `-lc`. Benjamin Feng's talk [_What's a Memory Allocator Anyway?_](https://www.youtube.com/watch?v=vHWiDx_l4V0) goes into more detail on this topic, and covers the implementation of allocators.
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/03.filesystem-stat.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end test "file stat" { const file = try std.fs.cwd().createFile( "junk_file2.txt", .{ .read = true }, ); defer file.close(); const stat = try file.stat(); try expect(stat.size == 0); try expect(stat.kind == .file); try expect(stat.ctime <= std.time.nanoTimestamp()); try expect(stat.mtime <= std.time.nanoTimestamp()); try expect(stat.atime <= std.time.nanoTimestamp()); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/02-arraylist.mdx
import CodeBlock from "@theme/CodeBlock"; import ArrayList from "!!raw-loader!./02.arraylist.zig"; # ArrayList The [`std.ArrayList`](https://ziglang.org/documentation/master/std/#std.ArrayList) is commonly used throughout Zig, and serves as a buffer that can change in size. `std.ArrayList(T)` is similar to C++'s `std::vector<T>` and Rust's `Vec<T>`. The `deinit()` method frees all of the ArrayList's memory. The memory can be read from and written to via its slice field - `.items`. Here we will introduce the usage of the testing allocator. This is a special allocator that only works in tests and can detect memory leaks. In your code, use whatever allocator is appropriate. <CodeBlock language="zig">{ArrayList}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01.allocators-alloc.zig
const std = @import("std"); const expect = std.testing.expect; test "allocation" { const allocator = std.heap.page_allocator; const memory = try allocator.alloc(u8, 100); defer allocator.free(memory); try expect(memory.len == 100); try expect(@TypeOf(memory) == []u8); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01.allocators-arena.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end test "arena allocator" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); _ = try allocator.alloc(u8, 1); _ = try allocator.alloc(u8, 10); _ = try allocator.alloc(u8, 100); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/03.filesystem-cwd-create.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end test "createFile, write, seekTo, read" { const file = try std.fs.cwd().createFile( "junk_file.txt", .{ .read = true }, ); defer file.close(); const bytes_written = try file.writeAll("Hello File!"); _ = bytes_written; var buffer: [100]u8 = undefined; try file.seekTo(0); const bytes_read = try file.readAll(&buffer); try expect(eql(u8, buffer[0..bytes_read], "Hello File!")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/14-formatting-specifiers.md
# Formatting specifiers [`std.fmt`](https://ziglang.org/documentation/master/std/#std;fmt) provides options for formatting various data types. `std.fmt.fmtSliceHexLower` and `std.fmt.fmtSliceHexUpper` provide hex formatting for strings as well as `{x}` and `{X}` for ints. ```zig const bufPrint = std.fmt.bufPrint; test "hex" { var b: [8]u8 = undefined; _ = try bufPrint(&b, "{X}", .{4294967294}); try expect(eql(u8, &b, "FFFFFFFE")); _ = try bufPrint(&b, "{x}", .{4294967294}); try expect(eql(u8, &b, "fffffffe")); _ = try bufPrint(&b, "{}", .{std.fmt.fmtSliceHexLower("Zig!")}); try expect(eql(u8, &b, "5a696721")); } ``` `{d}` performs decimal formatting for numeric types. ```zig test "decimal float" { var b: [4]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{d}", .{16.5}), "16.5", )); } ``` `{c}` formats a byte into an ascii character. ```zig test "ascii fmt" { var b: [1]u8 = undefined; _ = try bufPrint(&b, "{c}", .{66}); try expect(eql(u8, &b, "B")); } ``` `std.fmt.fmtIntSizeDec` and `std.fmt.fmtIntSizeBin` output memory sizes in metric (1000) and power-of-two (1024) based notation. ```zig test "B Bi" { var b: [32]u8 = undefined; try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1)}), "1B")); try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1)}), "1B")); try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1024)}), "1.024kB")); try expect(eql(u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1024)}), "1KiB")); try expect(eql( u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeDec(1024 * 1024 * 1024)}), "1.073741824GB", )); try expect(eql( u8, try bufPrint(&b, "{}", .{std.fmt.fmtIntSizeBin(1024 * 1024 * 1024)}), "1GiB", )); } ``` `{b}` and `{o}` output integers in binary and octal format. ```zig test "binary, octal fmt" { var b: [8]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{b}", .{254}), "11111110", )); try expect(eql( u8, try bufPrint(&b, "{o}", .{254}), "376", )); } ``` `{*}` performs pointer formatting, printing the address rather than the value. ```zig test "pointer fmt" { var b: [16]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{*}", .{@as(*u8, @ptrFromInt(0xDEADBEEF))}), "u8@deadbeef", )); } ``` `{e}` outputs floats in scientific notation. ```zig test "scientific" { var b: [16]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{e}", .{3.14159}), "3.14159e+00", )); } ``` `{s}` outputs strings. ```zig test "string fmt" { var b: [6]u8 = undefined; const hello: [*:0]const u8 = "hello!"; try expect(eql( u8, try bufPrint(&b, "{s}", .{hello}), "hello!", )); } ``` This list is non-exhaustive.
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/12-sorting.md
# Sorting The standard library provides utilities for in-place sorting slices. Its basic usage is as follows. ```zig test "sorting" { var data = [_]u8{ 10, 240, 0, 0, 10, 5 }; std.mem.sort(u8, &data, {}, comptime std.sort.asc(u8)); try expect(eql(u8, &data, &[_]u8{ 0, 0, 5, 10, 10, 240 })); std.mem.sort(u8, &data, {}, comptime std.sort.desc(u8)); try expect(eql(u8, &data, &[_]u8{ 240, 10, 10, 5, 0, 0 })); } ``` [`std.sort.asc`](https://ziglang.org/documentation/master/std/#std.sort.asc) and [`.desc`](https://ziglang.org/documentation/master/std/#std.sort.desc) create a comparison function for the given type at comptime; if non-numerical types should be sorted, the user must provide their own comparison function. [`std.mem.sort`](https://ziglang.org/documentation/master/std/#std.mem.sort) has a best case of O(n), and an average and worst case of O(n*log(n)).
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/05-formatting.mdx
import CodeBlock from "@theme/CodeBlock"; import Fmt from "!!raw-loader!./05.formatting-fmt.zig"; import Print from "!!raw-loader!./05.formatting-print.zig"; import ArrayPrint from "!!raw-loader!./05.formatting-array-print.zig"; import Custom from "!!raw-loader!./05.formatting-custom.zig"; # Formatting [`std.fmt`](https://ziglang.org/documentation/master/std/#std.fmt) provides ways to format data to and from strings. A basic example of creating a formatted string. The format string must be compile-time known. The `d` here denotes that we want a decimal number. <CodeBlock language="zig">{Fmt}</CodeBlock> Writers conveniently have a `print` method, which works similarly. <CodeBlock language="zig">{Print}</CodeBlock> Take a moment to appreciate that you now know from top to bottom how printing Hello World works. [`std.debug.print`](https://ziglang.org/documentation/master/std/#std.debug.print) works the same, except it writes to stderr and is protected by a mutex. {/* Code snippet not tested as it uses stdin/stdout */} ```zig // hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end test "hello world" { const out_file = std.io.getStdOut(); try out_file.writer().print( "Hello, {s}!\n", .{"World"}, ); } ``` We have used the `{s}` format specifier up until this point to print strings. Here, we will use `{any}`, which gives us the default formatting. <CodeBlock language="zig">{ArrayPrint}</CodeBlock> Let's create a type with custom formatting by giving it a `format` function. This function must be marked as `pub` so that std.fmt can access it (more on packages later). You may notice the usage of `{s}` instead of `{}` - this is the format specifier for strings (more on format specifiers later). This is used here as `{}` defaults to array printing over string printing. <CodeBlock language="zig">{Custom}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/07-random-numbers.md
# Random Numbers Here, we create a new prng using a 64-bit random seed. a, b, c, and d are given random values via this prng. The expressions giving c and d values are equivalent. `DefaultPrng` is `Xoroshiro128`; there are other prngs available in std.rand. ```zig test "random numbers" { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.posix.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); const rand = prng.random(); const a = rand.float(f32); const b = rand.boolean(); const c = rand.int(u8); const d = rand.intRangeAtMost(u8, 0, 255); //suppress unused constant compile error _ = .{ a, b, c, d }; } ``` Cryptographically secure random is also available. ```zig test "crypto random numbers" { const rand = std.crypto.random; const a = rand.float(f32); const b = rand.boolean(); const c = rand.int(u8); const d = rand.intRangeAtMost(u8, 0, 255); //suppress unused constant compile error _ = .{ a, b, c, d }; } ``` :::info We can now use our knowledge of std.rand and [make a guessing game together](/posts/a-guessing-game). :::
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01.allocators-fba.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end test "fixed buffer allocator" { var buffer: [1000]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buffer); const allocator = fba.allocator(); const memory = try allocator.alloc(u8, 100); defer allocator.free(memory); try expect(memory.len == 100); try expect(@TypeOf(memory) == []u8); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/05.formatting-custom.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; const test_allocator = std.testing.allocator; // hide-end const Person = struct { name: []const u8, birth_year: i32, death_year: ?i32, pub fn format( self: Person, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; try writer.print("{s} ({}-", .{ self.name, self.birth_year, }); if (self.death_year) |year| { try writer.print("{}", .{year}); } try writer.writeAll(")"); } }; test "custom fmt" { const john = Person{ .name = "John Carmack", .birth_year = 1970, .death_year = null, }; const john_string = try std.fmt.allocPrint( test_allocator, "{s}", .{john}, ); defer test_allocator.free(john_string); try expect(eql( u8, john_string, "John Carmack (1970-)", )); const claude = Person{ .name = "Claude Shannon", .birth_year = 1916, .death_year = 2001, }; const claude_string = try std.fmt.allocPrint( test_allocator, "{s}", .{claude}, ); defer test_allocator.free(claude_string); try expect(eql( u8, claude_string, "Claude Shannon (1916-2001)", )); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/06-json.md
# JSON Let's parse a JSON string into a struct type, using the streaming parser. ```zig const Place = struct { lat: f32, long: f32 }; test "json parse" { const parsed = try std.json.parseFromSlice( Place, test_allocator, \\{ "lat": 40.684540, "long": -74.401422 } , .{}, ); defer parsed.deinit(); const place = parsed.value; try expect(place.lat == 40.684540); try expect(place.long == -74.401422); } ``` And using stringify to turn arbitrary data into a string. ```zig test "json stringify" { const x = Place{ .lat = 51.997664, .long = -0.740687, }; var buf: [100]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buf); var string = std.ArrayList(u8).init(fba.allocator()); try std.json.stringify(x, .{}, string.writer()); try expect(eql(u8, string.items, \\{"lat":5.199766540527344e+01,"long":-7.406870126724243e-01} )); } ``` The JSON parser requires an allocator for javascript's string, array, and map types. ```zig test "json parse with strings" { const User = struct { name: []u8, age: u16 }; const parsed = try std.json.parseFromSlice(User, test_allocator, \\{ "name": "Joe", "age": 25 } , .{},); defer parsed.deinit(); const user = parsed.value; try expect(eql(u8, user.name, "Joe")); try expect(user.age == 25); } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/13-iterators.md
# Iterators It is a common idiom to have a struct type with a `next` function with an optional in its return type, so that the function may return a null to indicate that iteration is finished. [`std.mem.SplitIterator`](https://ziglang.org/documentation/master/std/#std.mem.SplitIterator) (and the subtly different [`std.mem.TokenIterator`](https://ziglang.org/documentation/master/std/#std.mem.TokenIterator)) is an example of this pattern. ```zig test "split iterator" { const text = "robust, optimal, reusable, maintainable, "; var iter = std.mem.split(u8, text, ", "); try expect(eql(u8, iter.next().?, "robust")); try expect(eql(u8, iter.next().?, "optimal")); try expect(eql(u8, iter.next().?, "reusable")); try expect(eql(u8, iter.next().?, "maintainable")); try expect(eql(u8, iter.next().?, "")); try expect(iter.next() == null); } ``` Some iterators have a `!?T` return type, as opposed to ?T. `!?T` requires that we unpack the error union before the optional, meaning that the work done to get to the next iteration may error. Here is an example of doing this with a loop. [`cwd`](https://ziglang.org/documentation/master/std/#std;fs.cwd) has to be opened with iterate permissions for the directory iterator to work. ```zig test "iterator looping" { var iter = (try std.fs.cwd().openIterableDir( ".", .{}, )).iterate(); var file_count: usize = 0; while (try iter.next()) |entry| { if (entry.kind == .file) file_count += 1; } try expect(file_count > 0); } ``` Here we will implement a custom iterator. This will iterate over a slice of strings, yielding the strings which contain a given string. ```zig const ContainsIterator = struct { strings: []const []const u8, needle: []const u8, index: usize = 0, fn next(self: *ContainsIterator) ?[]const u8 { const index = self.index; for (self.strings[index..]) |string| { self.index += 1; if (std.mem.indexOf(u8, string, self.needle)) |_| { return string; } } return null; } }; test "custom iterator" { var iter = ContainsIterator{ .strings = &[_][]const u8{ "one", "two", "three" }, .needle = "e", }; try expect(eql(u8, iter.next().?, "one")); try expect(eql(u8, iter.next().?, "three")); try expect(iter.next() == null); } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/04-readers-and-writers.mdx
import CodeBlock from "@theme/CodeBlock"; import Writer from "!!raw-loader!./04.readers-and-writers-writer.zig"; import Reader from "!!raw-loader!./04.readers-and-writers-reader.zig"; import Custom from "!!raw-loader!./04.readers-and-writers-custom.zig"; # Readers and Writers [`std.io.Writer`](https://ziglang.org/documentation/master/std/#std.io.Writer) and [`std.io.Reader`](https://ziglang.org/documentation/master/std/#std.io.Reader) provide standard ways of making use of IO. `std.ArrayList(u8)` has a `writer` method which gives us a writer. Let's use it. <CodeBlock language="zig">{Writer}</CodeBlock> Here we will use a reader to copy the file's contents into an allocated buffer. The second argument of [`readAllAlloc`](https://ziglang.org/documentation/master/std/#std.io.Reader.readAllAlloc) is the maximum size that it may allocate; if the file is larger than this, it will return `error.StreamTooLong`. <CodeBlock language="zig">{Reader}</CodeBlock> A common usecase for readers is to read until the next line (e.g. for user input). Here we will do this with the [`std.io.getStdIn()`](https://ziglang.org/documentation/master/std/#std.io.getStdIn) file. {/* Code snippet not tested as it uses stdin/stdout */} ```zig // hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end fn nextLine(reader: anytype, buffer: []u8) !?[]const u8 { var line = (try reader.readUntilDelimiterOrEof( buffer, '\n', )) orelse return null; // trim annoying windows-only carriage return character if (@import("builtin").os.tag == .windows) { return std.mem.trimRight(u8, line, "\r"); } else { return line; } } test "read until next line" { const stdout = std.io.getStdOut(); const stdin = std.io.getStdIn(); try stdout.writeAll( \\ Enter your name: ); var buffer: [100]u8 = undefined; const input = (try nextLine(stdin.reader(), &buffer)).?; try stdout.writer().print( "Your name is: \"{s}\"\n", .{input}, ); } ``` An [`std.io.Writer`](https://ziglang.org/documentation/master/std/#std.io.Writer) type consists of a context type, error set, and a write function. The write function must take in the context type and a byte slice. The write function must also return an error union of the Writer type's error set and the number of bytes written. Let's create a type that implements a writer. <CodeBlock language="zig">{Custom}</CodeBlock>
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01.allocators-create.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end test "allocator create/destroy" { const byte = try std.heap.page_allocator.create(u8); defer std.heap.page_allocator.destroy(byte); byte.* = 128; }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/15-advanced-formatting.md
--- pagination_next: build-system/build-modes --- # Advanced Formatting So far we have only covered formatting specifiers. Format strings actually follow this format, where between each pair of square brackets is a parameter you have to replace with something. `{[position][specifier]:[fill][alignment][width].[precision]}` | Name | Meaning | | --------- | -------------------------------------------------------------------------------- | | Position | The index of the argument that should be inserted | | Specifier | A type-dependent formatting option | | Fill | A single character used for padding | | Alignment | One of three characters < ^ or >; these are for left, middle and right alignment | | Width | The total width of the field (characters) | | Precision | How many decimals a formatted number should have | Position usage. ```zig test "position" { var b: [3]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{0s}{0s}{1s}", .{ "a", "b" }), "aab", )); } ``` Fill, alignment and width being used. ```zig test "fill, alignment, width" { var b: [6]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{s: <5}", .{"hi!"}), "hi! ", )); try expect(eql( u8, try bufPrint(&b, "{s:_^6}", .{"hi!"}), "_hi!__", )); try expect(eql( u8, try bufPrint(&b, "{s:!>4}", .{"hi!"}), "!hi!", )); } ``` Using a specifier with precision. ```zig test "precision" { var b: [4]u8 = undefined; try expect(eql( u8, try bufPrint(&b, "{d:.2}", .{3.14159}), "3.14", )); } ```
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/05.formatting-fmt.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end const test_allocator = std.testing.allocator; test "fmt" { const string = try std.fmt.allocPrint( test_allocator, "{d} + {d} = {d}", .{ 9, 10, 19 }, ); defer test_allocator.free(string); try expect(eql(u8, string, "9 + 10 = 19")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/09-threads.md
# Threads While Zig provides more advanced ways of writing concurrent and parallel code, [`std.Thread`](https://ziglang.org/documentation/master/std/#std.Thread) is available for making use of OS threads. Let's make use of an OS thread. ```zig fn ticker(step: u8) void { while (true) { std.time.sleep(1 * std.time.ns_per_s); tick += @as(isize, step); } } var tick: isize = 0; test "threading" { var thread = try std.Thread.spawn(.{}, ticker, .{@as(u8, 1)}); _ = thread; try expect(tick == 0); std.time.sleep(3 * std.time.ns_per_s / 2); try expect(tick == 1); } ``` Threads, however, aren't particularly useful without strategies for thread safety.
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/02.arraylist.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end const eql = std.mem.eql; const ArrayList = std.ArrayList; const test_allocator = std.testing.allocator; test "arraylist" { var list = ArrayList(u8).init(test_allocator); defer list.deinit(); try list.append('H'); try list.append('e'); try list.append('l'); try list.append('l'); try list.append('o'); try list.appendSlice(" World!"); try expect(eql(u8, list.items, "Hello World!")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/01.allocators-gpa.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; // hide-end test "GPA" { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer { const deinit_status = gpa.deinit(); //fail test; can't try in defer as defer is executed after we return if (deinit_status == .leak) expect(false) catch @panic("TEST FAIL"); } const bytes = try allocator.alloc(u8, 100); defer allocator.free(bytes); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/03.filesystem-make-dir-iterable.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end test "make dir" { try std.fs.cwd().makeDir("test-tmp"); var iter_dir = try std.fs.cwd().openDir( "test-tmp", .{ .iterate = true }, ); defer { iter_dir.close(); std.fs.cwd().deleteTree("test-tmp") catch unreachable; } _ = try iter_dir.createFile("x", .{}); _ = try iter_dir.createFile("y", .{}); _ = try iter_dir.createFile("z", .{}); var file_count: usize = 0; var iter = iter_dir.iterate(); while (try iter.next()) |entry| { if (entry.kind == .file) file_count += 1; } try expect(file_count == 3); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/02-standard-library/04.readers-and-writers-writer.zig
// hide-start const std = @import("std"); const expect = std.testing.expect; const eql = std.mem.eql; // hide-end const ArrayList = std.ArrayList; const test_allocator = std.testing.allocator; test "io writer usage" { var list = ArrayList(u8).init(test_allocator); defer list.deinit(); const bytes_written = try list.writer().write( "Hello World!", ); try expect(bytes_written == 12); try expect(eql(u8, list.items, "Hello World!")); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/01-language-basics/19.floats-conversion.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "int-float conversion" { const a: i32 = 0; const b = @as(f32, @floatFromInt(a)); const c = @as(i32, @intFromFloat(b)); try expect(c == a); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/01-language-basics/24.comptime-typeinfo.zig
// hide-start const expect = @import("std").testing.expect; //hide-end fn addSmallInts(comptime T: type, a: T, b: T) T { return switch (@typeInfo(T)) { .ComptimeInt => a + b, .Int => |info| if (info.bits <= 16) a + b else @compileError("ints too large"), else => @compileError("only ints accepted"), }; } test "typeinfo switch" { const x = addSmallInts(u16, 20, 30); try expect(@TypeOf(x) == u16); try expect(x == 50); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/01-language-basics/14.slices.zig
// hide-start const expect = @import("std").testing.expect; // hide-end fn total(values: []const u8) usize { var sum: usize = 0; for (values) |v| sum += v; return sum; } test "slices" { const array = [_]u8{ 1, 2, 3, 4, 5 }; const slice = array[0..3]; try expect(total(slice) == 6); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/01-language-basics/23.optionals-orelse-unreachable.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "orelse unreachable" { const a: ?f32 = 5; const b = a orelse unreachable; const c = a.?; try expect(b == c); try expect(@TypeOf(c) == f32); }
0
repos/zig.guide/website/versioned_docs/version-0.12
repos/zig.guide/website/versioned_docs/version-0.12/01-language-basics/18.integer-casting.zig
// hide-start const expect = @import("std").testing.expect; //hide-end test "@intCast" { const x: u64 = 200; const y = @as(u8, @intCast(x)); try expect(@TypeOf(y) == u8); }