### Compiling Zig Style Example (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md Provides the shell command to compile the `redundant_fqn.zig` source file, which contains a Zig code example demonstrating a specific style guide point regarding naming within namespaces. ```Shell $ zig build-exe redundant_fqn.zig ``` -------------------------------- ### Examples of Zig Naming Conventions (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md Presents a collection of Zig code examples illustrating various naming conventions outlined in the style guide, including snake_case for variables/namespaces, TitleCase for types/functions returning types, and camelCase for other functions. ```Zig const namespace_name = @import("dir_name/file_name.zig"); const TypeName = @import("dir_name/TypeName.zig"); var global_var: i32 = undefined; const const_name = 42; const primitive_type_alias = f32; const string_alias = []u8; const StructName = struct { field: i32, }; const StructAlias = StructName; fn functionName(param_name: TypeName) void { var functionPointer = functionName; functionPointer(); functionPointer = otherFunction; functionPointer(); } const functionAlias = functionName; fn ListTemplateFunction(comptime ChildType: type, comptime fixed_size: usize) type { return List(ChildType, fixed_size); } fn ShortList(comptime T: type, comptime n: usize) type { return struct { field_name: [n]T, fn methodName() void {} }; } // The word XML loses its casing when used in Zig identifiers. const xml_document = "\\n \\n \\n"; const XmlParser = struct { field: i32, }; // The initials BE (Big Endian) are just another word in Zig identifier names. fn readU32Be() u32 {} ``` -------------------------------- ### Running Zig Style Example Executable (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md Shows how to execute the compiled `redundant_fqn` program. The program prints the fully-qualified name of the `json.JsonValue` type, visually demonstrating the naming redundancy highlighted by the style guide. ```Shell $ ./redundant_fqn redundant_fqn.json.JsonValue ``` -------------------------------- ### Building and Running Zig Entry Point Example Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_5.md Provides the shell commands necessary to compile the `entry_point.zig` example into an executable and then run it, demonstrating the output of the `main` function. ```Shell $ zig build-exe entry_point.zig $ ./entry_point Hello, World! ``` -------------------------------- ### Defining SliceStart Struct - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_147.md Defines the `SliceStart` struct, representing the operation of getting the starting element of a slice. It contains references to the left-hand side operand (the slice or array being sliced) and the starting index (`start`). ```Zig pub const SliceStart = struct { lhs: Ref, start: Ref, }; ``` -------------------------------- ### Compiling and Running Zig Print Example (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_4.md Shows the shell commands needed to compile the `print.zig` file using `zig build-exe` and then execute the resulting binary. The output demonstrates the result of the `print` call with the formatted string and values. ```Shell $ zig build-exe print.zig $ ./print here is a string: 'foobar' here is a number: 1234 ``` -------------------------------- ### Building and Running Zig Example (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Provides the shell commands necessary to compile and execute the preceding Zig example code (`string_literals.zig`) and shows the expected output, demonstrating the behavior of string and character manipulations. ```Shell $ zig build-exe string_literals.zig $ ./string_literals *const [5:0]u8 5 e 0 true 128169 128175 ⚡ true true 0xfe 0x9f ``` -------------------------------- ### Rendering Standard Library Docs Shell Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Shows the command to launch a local web server rendering the Zig Standard Library documentation. Requires a Zig installation. ```Shell zig std ``` -------------------------------- ### Getting Emitted Include Tree Path Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_9.md Returns a `LazyPath` pointing to the directory where installed headers will be placed. If the necessary `WriteFiles` step hasn't been created yet for the include tree, this function initializes it and adds all currently registered installed headers to it before returning the path. ```Zig pub fn getEmittedIncludeTree(cs: *Compile) LazyPath { if (cs.installed_headers_include_tree) |wf| return wf.getDirectory(); const b = cs.step.owner; const wf = b.addWriteFiles(); cs.installed_headers_include_tree = wf; for (cs.installed_headers.items) |installation| { cs.addHeaderInstallationToIncludeTree(installation); } // The compile step itself does not need to depend on the write files step, // only dependent modules do. return wf.getDirectory(); } ``` -------------------------------- ### Building and Running Basic Values Example Shell Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Provides the shell commands to compile the `values.zig` file and run the resulting executable, showing the output demonstrating the various value types and their string representations printed by `std.debug.print`. Requires the Zig compiler and the source file. ```Shell $ zig build-exe values.zig $ ./values 1 + 1 = 2 7.0 / 3.0 = 2.3333333e0 false true false optional 1 type: ?[]const u8 value: null optional 2 type: ?[]const u8 value: hi error union 1 type: anyerror!i32 value: error.ArgNotFound error union 2 type: anyerror!i32 value: 1234 ``` -------------------------------- ### Getting String Bytes from ZIR Data (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_147.md Retrieves a string slice from the main `Zir` code structure using the stored `start` offset and `len`. The `start` field is treated as an index into the `string_bytes` array, and `len` specifies the number of bytes to extract. ```zig pub fn get(self: @This(), code: Zir) []const u8 { return code.string_bytes[@intFromEnum(self.start)..][0..self.len]; } ``` -------------------------------- ### Testing BigInt Byte Swap - Setup - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_71.md Starts the test suite for big integer byte swapping. Initializes a `Managed` big integer instance using the testing allocator. The actual test cases likely follow this setup, calling the `byteSwapTest` helper. ```Zig test "big int byte swap" { var a = try Managed.initSet(testing.allocator, 0x01_ffffffff_ffffffff_ffffffff); defer a.deinit(); ``` -------------------------------- ### Running WASI Preopens Example with wasmtime (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md Shows how to execute the compiled WASI module (`wasi_preopens.wasm`) using the `wasmtime` runtime. The `--dir=.` flag preopens the current directory, demonstrating how it appears in the list of preopens printed by the program. ```Shell $ wasmtime --dir=. wasi_preopens.wasm 0: stdin 1: stdout 2: stderr 3: . ``` -------------------------------- ### Installing Library Headers Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_9.md Forwards headers marked for installation from a library compilation artifact to the current compilation artifact. This ensures that when a module links with the current artifact, it automatically gets the necessary header include paths. Requires both compile targets to be valid and handles memory allocation failures. ```Zig /// Forwards all headers marked for installation from `lib` to this artifact. /// When a module links with this artifact, all headers marked for installation are added to that /// module's include search path. pub fn installLibraryHeaders(cs: *Compile, lib: *Compile) void { assert(lib.kind == .lib); for (lib.installed_headers.items) |installation| { const installation_copy = installation.dupe(lib.step.owner); cs.installed_headers.append(installation_copy) catch @panic("OOM"); cs.addHeaderInstallationToIncludeTree(installation_copy); installation_copy.getSource().addStepDependencies(&cs.step); } } ``` -------------------------------- ### Compiler-Generated Function for PerformFn Specialization ('w') | Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_4.md This snippet shows the optimized runtime code generated by the compiler for the `performFn` when its `comptime` parameter `prefix_char` is `'w'`. Since the compile-time evaluation found no functions starting with 'w', the generated function contains no calls to the command functions, effectively just returning the starting value. ```Zig // From the line: // expect(performFn('w', 99) == 99); fn performFn(start_value: i32) i32 { var result: i32 = start_value; _ = &result; return result; } ``` -------------------------------- ### Building and Running C-Compatible Zig Entry Point Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_5.md Provides the shell commands to compile the `libc_export_entry_point.zig` example, specifically including the `-lc` flag to link with the C standard library, and then execute the resulting program. ```Shell $ zig build-exe libc_export_entry_point.zig -lc $ ./libc_export_entry_point Hello! argv[0] is './libc_export_entry_point' ``` -------------------------------- ### Getting Compile Dependencies in Zig Build Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_9.md This public function recursively gathers all `Step.Compile` dependencies for a given starting step, including the start step itself. It uses a hash map to track visited steps and avoid infinite loops. The `chase_dynamic` parameter controls whether dependencies through dynamic libraries are followed. ```Zig pub fn getCompileDependencies(start: *Compile, chase_dynamic: bool) []const *Compile { const arena = start.step.owner.graph.arena; var compiles: std.AutoArrayHashMapUnmanaged(*Compile, void) = .empty; var next_idx: usize = 0; compiles.putNoClobber(arena, start, {}) catch @panic("OOM"); while (next_idx < compiles.count()) { const compile = compiles.keys()[next_idx]; next_idx += 1; for (compile.root_module.getGraph().modules) |mod| { for (mod.link_objects.items) |lo| { switch (lo) { .other_step => |other_compile| { if (!chase_dynamic and other_compile.isDynamicLibrary()) continue; compiles.put(arena, other_compile, {}) catch @panic("OOM"); }, else => {}, } } } } return compiles.keys(); } ``` -------------------------------- ### Building and Running Executable Shell Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Provides the shell commands to compile the `hello.zig` file into an executable and then run it, demonstrating the output. Requires the Zig compiler and the source file. ```Shell $ zig build-exe hello.zig $ ./hello Hello, world! ``` -------------------------------- ### Get Vector Kind from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Determines and returns the kind of vector (normal or scalable) for a vector Type based on its tag obtained from the builder. ```Zig pub fn vectorKind(self: Type, builder: *const Builder) Type.Vector.Kind { return switch (self.tag(builder)) { .vector => .normal, .scalable_vector => .scalable, else => unreachable, }; } ``` -------------------------------- ### Building and Running Debug Executable Shell Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Provides the shell commands to compile the `hello_again.zig` file into an executable and then run it, demonstrating the output from the `std.debug.print` example. Requires the Zig compiler and the source file. ```Shell $ zig build-exe hello_again.zig $ ./hello_again Hello, world! ``` -------------------------------- ### Get Function Kind from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Determines and returns the kind of function (normal or vararg) for a function Type based on its tag obtained from the builder. ```Zig pub fn functionKind(self: Type, builder: *const Builder) Type.Function.Kind { return switch (self.tag(builder)) { .function => .normal, .vararg_function => .vararg, else => unreachable, }; } ``` -------------------------------- ### Building and Running Zig Panic Handler Example Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_5.md Provides the shell commands to compile the `panic_handler.zig` example and then execute it, demonstrating the output produced by the custom panic handler when an integer overflow occurs. ```Shell $ zig build-exe panic_handler.zig $ ./panic_handler Panic! integer overflow ``` -------------------------------- ### Implementing Hello World with Syscalls using Zig Assembly Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_4.md This snippet demonstrates implementing a basic 'Hello, World' program in Zig using inline assembly to directly invoke Linux system calls (`write` and `exit`). It defines necessary constants for the syscall numbers and standard output file descriptor. ```Zig pub fn main() noreturn { const msg = "hello world\n"; _ = syscall3(SYS_write, STDOUT_FILENO, @intFromPtr(msg), msg.len); _ = syscall1(SYS_exit, 0); unreachable; } pub const SYS_write = 1; pub const SYS_exit = 60; pub const STDOUT_FILENO = 1; pub fn syscall1(number: usize, arg1: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize), : [number] "{rax}" (number), [arg1] "{rdi}" (arg1), : "rcx", "r11" ); } pub fn syscall3(number: usize, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("syscall" : [ret] "={rax}" (-> usize), : [number] "{rax}" (number), [arg1] "{rdi}" (arg1), [arg2] "{rsi}" (arg2), [arg3] "{rdx}" (arg3), : "rcx", "r11" ); } ``` -------------------------------- ### Get Type Tag from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Retrieves the primary Tag associated with a Type enum value by indexing into the builder's type_items array. ```Zig pub fn tag(self: Type, builder: *const Builder) Tag { return builder.type_items.items[@intFromEnum(self)].tag; } ``` -------------------------------- ### Zig Build Script for C Library/Executable Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md This `build.zig` script uses the Zig Build System to compile `mathtest.zig` as a shared library and `test.c` as an executable. It links the C executable against the Zig library and the system C library. The script defines steps to build the executable and includes a run step for testing, demonstrating how to manage multi-language projects with Zig. ```Zig const std = @import("std"); pub fn build(b: *std.Build) void { const lib = b.addSharedLibrary(.{ .name = "mathtest", .root_source_file = b.path("mathtest.zig"), .version = .{ .major = 1, .minor = 0, .patch = 0 }, }); const exe = b.addExecutable(.{ .name = "test", }); exe.addCSourceFile(.{ .file = b.path("test.c"), .flags = &.{"-std=c99"} }); exe.linkLibrary(lib); exe.linkSystemLibrary("c"); b.default_step.dependOn(&exe.step); const run_cmd = exe.run(); const test_step = b.step("test", "Test the program"); test_step.dependOn(&run_cmd.step); } ``` -------------------------------- ### Defining UEFI UDPv6 Protocol Binding (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_89.md Defines the GUID constant for the UEFI UDPv6 Service Binding Protocol and imports the associated UDPv6 protocol definition. Similar to IPv6, this GUID is used to locate or install instances of the UDPv6 service binding protocol, facilitating UDP communication over IPv6 within UEFI. ```zig pub const Udp6ServiceBinding = ServiceBinding(.{ .time_low = 0x66ed4721, .time_mid = 0x3c98, .time_high_and_version = 0x4d3e, .clock_seq_high_and_reserved = 0x81, .clock_seq_low = 0xe3, .node = [_]u8{ 0xd0, 0x3d, 0xd3, 0x9a, 0x72, 0x54 }, }); pub const Udp6 = @import("protocol/udp6.zig").Udp6; ``` -------------------------------- ### C-Style Entry Point Handling and Setup (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_107.md This `main` function serves as a C-style entry point (`callconv(.c)`), designed to be called from the operating system or C runtime. It parses command-line arguments and environment variables from C pointers, performs platform-specific setup like stack expansion on Linux by finding ELF headers, and then delegates execution to `callMainWithArgs`. ```Zig fn main(c_argc: c_int, c_argv: [*][*:0]c_char, c_envp: [*:null]?[*:0]c_char) callconv(.c) c_int { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @as([*][*:0]u8, @ptrCast(c_envp))[0..env_count]; if (builtin.os.tag == .linux) { const at_phdr = std.c.getauxval(elf.AT_PHDR); const at_phnum = std.c.getauxval(elf.AT_PHNUM); const phdrs = (@as([*]elf.Phdr, @ptrFromInt(at_phdr)))[0..at_phnum]; expandStackSize(phdrs); } return callMainWithArgs(@as(usize, @intCast(c_argc)), @as([*][*:0]u8, @ptrCast(c_argv)), envp); } ``` -------------------------------- ### Defining UEFI IPv6 Protocol Binding (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_89.md Defines the GUID (Globally Unique Identifier) constant for the UEFI IPv6 Service Binding Protocol and imports the associated IPv6 protocol definitions. This GUID is used to locate or install instances of the IPv6 service binding protocol within the UEFI environment, enabling IPv6 network functionality. ```zig pub const Ip6ServiceBinding = ServiceBinding(.{ .time_low = 0xec835dd3, .time_mid = 0xfe0f, .time_high_and_version = 0x617b, .clock_seq_high_and_reserved = 0xa6, .clock_seq_low = 0x21, .node = [_]u8{ 0xb3, 0x50, 0xc3, 0xe1, 0x33, 0x88 }, }); pub const Ip6 = @import("protocol/ip6.zig").Ip6; pub const Ip6Config = @import("protocol/ip6_config.zig").Ip6Config; ``` -------------------------------- ### Iterating Over Multiple Collections with For Loop - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_3.md This snippet demonstrates iterating over two collections simultaneously using a single `for` loop. It requires that all collections specified have equal lengths at the start of the loop. ```Zig test "multi object for" { const items = [_]usize{ 1, 2, 3 }; const items2 = [_]usize{ 4, 5, 6 }; var count: usize = 0; // Iterate over multiple objects. // All lengths must be equal at the start of the loop, otherwise detectable // illegal behavior occurs. for (items, items2) |i, j| { count += i + j; } try expect(count == 21); } ``` -------------------------------- ### Rendering LibC Installation Config Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_131.md This function takes a `LibCInstallation` struct and prints its contents to an output stream in the key=value configuration file format. It includes comments above each field explaining its purpose, mirroring the documentation in the source code. ```Zig pub fn render(self: LibCInstallation, out: anytype) !void { @setEvalBranchQuota(4000); const include_dir = self.include_dir orelse ""; const sys_include_dir = self.sys_include_dir orelse ""; const crt_dir = self.crt_dir orelse ""; const msvc_lib_dir = self.msvc_lib_dir orelse ""; const kernel32_lib_dir = self.kernel32_lib_dir orelse ""; const gcc_dir = self.gcc_dir orelse ""; try out.print( "\\# The directory that contains `stdlib.h`.\n" + // "\\# On POSIX-like systems, include directories be found with: `cc -E -Wp,-v -xc /dev/null`\n" + // "\\include_dir={s}\n" + // "\\\n" + // "\\# The system-specific include directory. May be the same as `include_dir`.\n" + // "\\# On Windows it's the directory that includes `vcruntime.h`.\n" + // "\\# On POSIX it's the directory that includes `sys/errno.h`.\n" + // "\\sys_include_dir={s}\n" + // "\\\n" + // "\\# The directory that contains `crt1.o` or `crt2.o`.\n" + // "\\# On POSIX, can be found with `cc -print-file-name=crt1.o`.\n" + // "\\# Not needed when targeting MacOS.\n" + // "\\crt_dir={s}\n" + // "\\\n" + // "\\# The directory that contains `vcruntime.lib`.\n" + // "\\# Only needed when targeting MSVC on Windows.\n" + // "\\msvc_lib_dir={s}\n" + // "\\\n" + // "\\# The directory that contains `kernel32.lib`.\n" + // "\\# Only needed when targeting MSVC on Windows.\n" + // "\\kernel32_lib_dir={s}\n" + // "\\\n" + // "\\# The directory that contains `crtbeginS.o` and `crtendS.o`\n" + // "\\# Only needed when targeting Haiku.\n" + // "\\gcc_dir={s}\n" + // "\\\n" , .{ include_dir, sys_include_dir, crt_dir, msvc_lib_dir, kernel32_lib_dir, gcc_dir, }); } ``` -------------------------------- ### Building and Running Zig Assembly Example (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_4.md This snippet provides the shell commands necessary to compile the Zig source file containing inline assembly (`inline_assembly.zig`) for the x86_64 Linux target and then execute the resulting binary. ```Shell $ zig build-exe inline_assembly.zig -target x86_64-linux $ ./inline_assembly hello world ``` -------------------------------- ### Get Function Return Type from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Retrieves the return Type for a function Type from the builder's extra data. Asserts that the type is a function type. ```Zig pub fn functionReturn(self: Type, builder: *const Builder) Type { const item = builder.type_items.items[@intFromEnum(self)]; switch (item.tag) { .function, .vararg_function, => return builder.typeExtraData(Type.Function, item.data).ret, else => unreachable, } } ``` -------------------------------- ### Printing to Standard Output Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Demonstrates importing the standard library and writing "Hello, world!" to standard output using the `std.io.getStdOut().writer()` API. Shows basic error handling with `!` and `try`. ```Zig const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {s}!\n", .{"world"}); } ``` -------------------------------- ### Getting Next Iterator Element in Zig Test Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_56.md Gets the next element from an iterator `it` using `it.next()`. The `.?` operator attempts to unwrap an optional, causing a panic if it's `null`. This snippet shows the start of an assertion using `std.testing` after retrieving the next element. Requires an iterator object `it`. Input: iterator; Output: the next element or panic. ```Zig const second = it.next().?; try std.testing ``` -------------------------------- ### Adding System Command Step Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_5.md Initializes a `Step.Run` build step to execute an arbitrary system command. It takes a `Build` context and an array of command-line arguments (`argv`), where the first element must be the executable path. It asserts that `argv` is not empty. It returns the configured `Step.Run` step. Note that this introduces a system dependency; `Step.Compile.run` is preferred for running executables built by the current project. ```Zig /// Initializes a `Step.Run` with argv, which must at least have the path to the /// executable. More command line arguments can be added with `addArg`, /// `addArgs`, and `addArtifactArg`. /// Be careful using this function, as it introduces a system dependency. /// To run an executable built with zig build, see `Step.Compile.run`. pub fn addSystemCommand(b: *Build, argv: []const []const u8) *Step.Run { assert(argv.len >= 1); const run_step = Step.Run.create(b, b.fmt("run {s}", .{argv[0]})); run_step.addArgs(argv); return run_step; } ``` -------------------------------- ### Get Function Parameters from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Retrieves a slice containing the parameter Types for a function Type from the builder's extra data. Asserts that the type is a function type. ```Zig pub fn functionParameters(self: Type, builder: *const Builder) []const Type { const item = builder.type_items.items[@intFromEnum(self)]; switch (item.tag) { .function, .vararg_function, => { var extra = builder.typeExtraDataTrail(Type.Function, item.data); return extra.trail.next(extra.data.params_len, Type, builder); }, else => unreachable, } } ``` -------------------------------- ### Get WipMembers Fields Slice - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_126.md Returns a slice of the `WipMembers` payload containing the stored field data. The slice starts at `field_bits_start` and ends at `fields_end`. ```Zig fn fieldsSlice(self: *Self) []u32 { return self.payload.items[self.field_bits_start..self.fields_end]; } ``` -------------------------------- ### Compiling Zig WASI Preopens Example (Shell) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_6.md Provides the shell command to compile the `wasi_preopens.zig` source file into a WebAssembly executable specifically targeting the WASI environment using the `zig build-exe` command and the `-target wasm32-wasi` flag. ```Shell $ zig build-exe wasi_preopens.zig -target wasm32-wasi ``` -------------------------------- ### Getting Target Layout Type (Placeholder) in Builder (Zig) Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md A placeholder function intended to determine the target-specific memory layout type for a given type. Currently unimplemented and always panics. ```Zig pub fn targetLayoutType(self: Type, builder: *const Builder) Type { _ = self; _ = builder; @panic("TODO: implement targetLayoutType"); } ``` -------------------------------- ### Get Error Name String (@errorName) in Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_4.md Returns the string representation of an error value. If `@errorName` is not used or is used only with compile-time known values, no error name table is generated in the binary. ```Zig @errorName(err: anyerror) [:0]const u8 ``` -------------------------------- ### Defining C-Compatible Entry Point (export fn main) in Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_5.md Demonstrates how to define an `export fn main` that matches the standard C `main` function signature, allowing the Zig program to be used as the entry point when linking with C libraries that expect this format. Shows accessing command-line arguments. ```Zig pub export fn main(argc: c_int, argv: [*]const [*:0]const u8) c_int { const args = argv[0..@intCast(argc)]; std.debug.print("Hello! argv[0] is '{s}'\n", .{args[0]}); return 0; } const std = @import("std"); ``` -------------------------------- ### Get _DYNAMIC Symbol Address - ARM/Thumb Assembly Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_85.md This snippet contains the ARM and Thumb architecture-specific inline assembly for `getDynamicSymbol`. It uses a clever trick with `ldr` and a label (`1f`) to load the address of `_DYNAMIC` relative to the current PC. The result is then added to the PC to get the absolute address, stored in `%[ret]` (a pointer to `elf.Dyn`). This handles limited offset ranges of `ldr`. ```Assembly \\ .weak _DYNAMIC \\ .hidden _DYNAMIC \\ ldr %[ret], 1f \\ add %[ret], pc \\ b 2f \\ 1: .word _DYNAMIC-1b \\ 2: : [ret] "=r" (-> [*]elf.Dyn), ``` -------------------------------- ### Main Function and Argument Parsing in Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_59.md The `main` function serves as the entry point for the benchmark program. It sets up a fixed-buffer allocator, parses command-line arguments using `std.process.argsAlloc`, and processes various options like `--mode`, `--seed`, `--filter`, `--count`, `--key-size`, and flags for selecting specific test modes. ```Zig pub fn main() !void { const stdout = std.io.getStdOut().writer(); var buffer: [1024]u8 = undefined; var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]); const args = try std.process.argsAlloc(fixed.allocator()); var filter: ?[]u8 = ""; var count: usize = mode(128 * MiB); var key_size: ?usize = null; var seed: u32 = 0; var test_small_key_only = false; var test_iterative_only = false; var test_arrays = false; const default_small_key_size = 32; var i: usize = 1; while (i < args.len) : (i += 1) { if (std.mem.eql(u8, args[i], "--mode")) { try stdout.print("{}\n", .{builtin.mode}); return; } else if (std.mem.eql(u8, args[i], "--seed")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } seed = try std.fmt.parseUnsigned(u32, args[i], 10); // we seed later } else if (std.mem.eql(u8, args[i], "--filter")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } filter = args[i]; } else if (std.mem.eql(u8, args[i], "--count")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } const c = try std.fmt.parseUnsigned(usize, args[i], 10); count = c * MiB; } else if (std.mem.eql(u8, args[i], "--key-size")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } key_size = try std.fmt.parseUnsigned(usize, args[i], 10); if (key_size.? > block_size) { try stdout.print("key_size cannot exceed block size of {}\n", .{block_size}); std.process.exit(1); } } else if (std.mem.eql(u8, args[i], "--iterative-only")) { test_iterative_only = true; } else if (std.mem.eql(u8, args[i], "--small-key-only")) { test_small_key_only = true; } else if (std.mem.eql(u8, args[i], "--include-array")) { test_arrays = true; } else if (std.mem.eql(u8, args[i], "--help")) { usage(); return; } else { ``` -------------------------------- ### Initializing the Server Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_143.md Initializes the server state using the provided options. It sets up the input and output file handles and initializes the dynamic linear FIFO for receiving data, then serves the zig version message. ```Zig pub fn init(options: Options) !Server { var s: Server = .{ .in = options.in, .out = options.out, .receive_fifo = std.fifo.LinearFifo(u8, .Dynamic).init(options.gpa), }; try s.serveStringMessage(.zig_version, options.zig_version); return s; } ``` -------------------------------- ### Test Setup for File Overwrite Scenario in Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_108.md This code snippet starts a test function intended to verify that extracting a tar archive does not incorrectly overwrite existing files in a directory structure. The snippet includes comments describing the initial file system setup and the tar command used to create the test archive, but the test logic itself is not present in this provided text. ```Zig test "should not overwrite existing file" { // Starting from this folder structure: // $ tree root // root // ├── a // │   └── b // │   └── c // │   └── file.txt // └── d // └── b // └── c // └── file.txt // // Packed with command: // $ cd root; tar cf overwrite_file.tar * } ``` -------------------------------- ### Getting Scanner Stack Height Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_66.md A simple passthrough to `std.json.Scanner.stackHeight()`. Returns the current nesting depth of objects (`{}`) and arrays (`[]`) that the scanner is inside. Useful for matching start and end container tokens. ```Zig pub fn stackHeight(self: *const @This()) usize { return self.scanner.stackHeight(); } ``` -------------------------------- ### Main Program Entry Point Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_26.md The main function parses command-line arguments to configure benchmarking (`--mode`, `--seed`, `--filter`, `--help`). It allocates memory using an arena allocator, processes the arguments, and then iterates through predefined lists of cryptographic primitives (hashes, macs, etc.), running benchmarks for each (optionally filtered) and printing the results to standard output. ```Zig pub fn main() !void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const arena_allocator = arena.allocator(); const args = try std.process.argsAlloc(arena_allocator); var filter: ?[]u8 = ""; var i: usize = 1; while (i < args.len) : (i += 1) { if (std.mem.eql(u8, args[i], "--mode")) { try stdout.print("{}\n", .{builtin.mode}); return; } else if (std.mem.eql(u8, args[i], "--seed")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } const seed = try std.fmt.parseUnsigned(u32, args[i], 10); prng.seed(seed); } else if (std.mem.eql(u8, args[i], "--filter")) { i += 1; if (i == args.len) { usage(); std.process.exit(1); } filter = args[i]; } else if (std.mem.eql(u8, args[i], "--help")) { usage(); return; } else { usage(); std.process.exit(1); } } inline for (hashes) |H| { if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) { const throughput = try benchmarkHash(H.ty, mode(128 * MiB)); try stdout.print("{s:>17}: {:10} MiB/s\n", .{ H.name, throughput / (1 * MiB) }); } } inline for (macs) |M| { if (filter == null or std.mem.indexOf(u8, M.name, filter.?) != null) { const throughput = try benchmarkMac(M.ty, mode(128 * MiB)); try stdout.print("{s:>17}: {:10} MiB/s\n", .{ M.name, throughput / (1 * MiB) }); } } inline for (exchanges) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkKeyExchange(E.ty, mode(1000)); try stdout.print("{s:>17}: {:10} exchanges/s\n", .{ E.name, throughput }); } } inline for (signatures) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkSignature(E.ty, mode(1000)); try stdout.print("{s:>17}: {:10} signatures/s\n", .{ E.name, throughput }); } } inline for (signature_verifications) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkSignatureVerification(E.ty, mode(1000)); try stdout.print("{s:>17}: {:10} verifications/s\n", .{ E.name, throughput }); } } inline for (batch_signature_verifications) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkBatchSignatureVerification(E.ty, mode(1000)); try stdout.print("{s:>17}: {:10} verifications/s (batch)\n", .{ E.name, throughput }); } } inline for (aeads) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkAead(E.ty, mode(128 * MiB)); try stdout.print("{s:>17}: {:10} MiB/s\n", .{ E.name, throughput / (1 * MiB) }); } } inline for (aes) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkAes(E.ty, mode(100000000)); try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput }); } } inline for (aes8) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkAes8(E.ty, mode(10000000)); try stdout.print("{s:>17}: {:10} ops/s\n", .{ E.name, throughput }); } } inline for (pwhashes) |H| { if (filter == null or std.mem.indexOf(u8, H.name, filter.?) != null) { const throughput = try benchmarkPwhash(arena_allocator, H.ty, H.params, mode(64)); try stdout.print("{s:>17}: {d:10.3} s/ops\n", .{ H.name, throughput }); } } inline for (kems) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkKem(E.ty, mode(1000)); try stdout.print("{s:>17}: {:10} encaps/s\n", .{ E.name, throughput }); } } inline for (kems) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkKemDecaps(E.ty, mode(25000)); try stdout.print("{s:>17}: {:10} decaps/s\n", .{ E.name, throughput }); } } inline for (kems) |E| { if (filter == null or std.mem.indexOf(u8, E.name, filter.?) != null) { const throughput = try benchmarkKemKeyGen(E.ty, mode(25000)); try stdout.print("{s:>17}: {:10} keygen/s\n", .{ E.name, throughput }); } } } ``` -------------------------------- ### Building and Running Comments Example Shell Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/website_part_1.md Provides the shell commands to compile the `comments.zig` file and run the resulting executable, showing that the commented-out print statement is not executed. Requires the Zig compiler and the source file. ```Shell $ zig build-exe comments.zig $ ./comments Hello, world! ``` -------------------------------- ### Get Unnamed Type Tag from Builder - Zig Source: https://github.com/jedisct1/zig-for-mcp/blob/main/doc/split/zig-stdlib_part_132.md Retrieves the 'unnamed' tag for a Type. For named structures, it recursively resolves to the tag of the underlying body type; otherwise, it returns the direct tag. ```Zig pub fn unnamedTag(self: Type, builder: *const Builder) Tag { const item = builder.type_items.items[@intFromEnum(self)]; return switch (item.tag) { .named_structure => builder.typeExtraData(Type.NamedStructure, item.data).body .unnamedTag(builder), else => item.tag, }; } ```