### Install Zig Executable and Build Arguments Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Installs the Zig executable, build arguments, working directory, and install prefix using a CMake script. This makes these variables available in the installed environment. ```cmake set(ZIG_EXECUTABLE "$") install(CODE "set(ZIG_EXECUTABLE \"${ZIG_EXECUTABLE}\")") install(CODE "set(ZIG_BUILD_ARGS \"${ZIG_BUILD_ARGS}\")") install(CODE "set(ZIG2_WORKING_DIR \"${ZIG2_WORKING_DIR}\")") install(CODE "set(CMAKE_INSTALL_PREFIX \"${CMAKE_INSTALL_PREFIX}\")") install(SCRIPT cmake/install.cmake) ``` -------------------------------- ### Zig Dev Kit Download URL Example Source: https://github.com/dkb/zig/blob/master/README.md Example URL format for downloading the Windows Zig Compiler Dev Kit. Replace $VERSION with the appropriate version number. ```text https://ziglang.org/deps/zig+llvm+lld+clang-x86_64-windows-gnu-$VERSION.zip ``` -------------------------------- ### Build and Install with MSBuild Source: https://github.com/dkb/zig/blob/master/README.md Build the project using MSBuild with the Release configuration and install the artifacts. ```bat msbuild -p:Configuration=Release INSTALL.vcxproj ``` -------------------------------- ### Zig Base64 Encoding Example Source: https://context7.com/dkb/zig/llms.txt Demonstrates how to encode a string into Base64 format using Zig's `std.base64.standard.Encoder`. ```zig const std = @import("std"); const base64 = std.base64; const testing = std.testing; test "base64 encoding" { const input = "Hello, World!"; var encoded: [100]u8 = undefined; const encoded_slice = base64.standard.Encoder.encode(&encoded, input); try testing.expectEqualStrings("SGVsbG8sIFdvcmxkIQ==", encoded_slice); } ``` -------------------------------- ### Build with Ninja Source: https://github.com/dkb/zig/blob/master/README.md Install the build artifacts using Ninja after CMake configuration. ```bat ninja install ``` -------------------------------- ### Zig Base64 Decoding Example Source: https://context7.com/dkb/zig/llms.txt Shows how to decode a Base64 encoded string back to its original form using Zig's `std.base64.standard.Decoder`. ```zig const std = @import("std"); const base64 = std.base64; const testing = std.testing; test "base64 decoding" { const encoded = "SGVsbG8sIFdvcmxkIQ=="; var decoded: [100]u8 = undefined; const decoded_slice = try base64.standard.Decoder.decode(&decoded, encoded); try testing.expectEqualStrings("Hello, World!", decoded_slice); } ``` -------------------------------- ### Example Huffman Encoding Sequence Source: https://github.com/dkb/zig/blob/master/lib/std/compress/testdata/rfc8478.txt Shows the encoding of the literal sequence '0145' using the previously defined prefix codes. The example includes padding to form a complete byte sequence. ```text +---------+----------+ | Symbol | Encoding | +---------+----------+ | 5 | 0000 | +---------+----------+ | 4 | 0001 | +---------+----------+ | 1 | 01 | +---------+----------+ | 0 | 1 | +---------+----------+ | Padding | 00001 | +---------+----------+ ``` -------------------------------- ### Zig Fixed Buffer Allocator Example Source: https://context7.com/dkb/zig/llms.txt Shows the FixedBufferAllocator, which allocates from a pre-defined buffer. Useful for embedded systems or scenarios with known memory limits. ```zig const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const testing = std.testing; test "fixed buffer allocator" { var buffer: [1024]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buffer); const allocator = fba.allocator(); const slice = try allocator.alloc(u8, 100); try testing.expectEqual(@as(usize, 100), slice.len); } ``` -------------------------------- ### Build Zig from Source with CMake Source: https://github.com/dkb/zig/blob/master/README.md Standard CMake build process for compiling Zig from source. Ensure CMake and system toolchains are installed. LLVM development libraries are required. ```sh mkdir build cd build cmake .. make install ``` -------------------------------- ### Configure and Build LLD (Release Mode) Source: https://github.com/dkb/zig/blob/master/README.md Configures and builds the LLD linker in release mode. This command sets installation and prefix paths, and specifies release runtime libraries. ```bat mkdir C:\Users\Andy\lld-21.0.0.src\build-release cd C:\Users\Andy\lld-21.0.0.src\build-release "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:\Users\Andy\llvm+clang+lld-14.0.6-x86_64-windows-msvc-release-mt -DCMAKE_PREFIX_PATH=C:\Users\Andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-release-mt -DCMAKE_BUILD_TYPE=Release -DLLVM_USE_CRT_RELEASE=MT msbuild /m -p:Configuration=Release INSTALL.vcxproj ``` -------------------------------- ### Zig StringHashMap Usage Example Source: https://context7.com/dkb/zig/llms.txt Illustrates how to use StringHashMap for key-value storage with string keys. Includes insertion, retrieval, and iteration. Requires the testing allocator. ```zig const std = @import("std"); const StringHashMap = std.StringHashMap; const AutoHashMap = std.AutoHashMap; const testing = std.testing; test "StringHashMap usage" { var map = StringHashMap(i32).init(testing.allocator); defer map.deinit(); try map.put("hello", 42); try map.put("world", 100); const value = map.get("hello"); try testing.expectEqual(@as(?i32, 42), value); // Check if key exists try testing.expect(map.contains("world")); try testing.expect(!map.contains("missing")); // Iterate over entries var iterator = map.iterator(); while (iterator.next()) |entry| { _ = entry.key_ptr.*; _ = entry.value_ptr.*; } } ``` -------------------------------- ### Zig AutoHashMap with Integer Keys Example Source: https://context7.com/dkb/zig/llms.txt Demonstrates AutoHashMap with integer keys and string slice values. Requires the testing allocator. ```zig const std = @import("std"); const StringHashMap = std.StringHashMap; const AutoHashMap = std.AutoHashMap; const testing = std.testing; test "AutoHashMap with integer keys" { var map = AutoHashMap(u32, []const u8).init(testing.allocator); defer map.deinit(); try map.put(1, "one"); try map.put(2, "two"); try testing.expectEqualStrings("one", map.get(1).?); } ``` -------------------------------- ### Set Default Installation Prefix in CMake Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Configures the installation directory for the project, defaulting to a 'stage3' subdirectory within the binary directory. This allows for isolated installations. ```cmake if(NOT CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/stage3" CACHE PATH "Directory to install zig to" FORCE) endif() ``` -------------------------------- ### Example 2-Byte Bitstream Source: https://github.com/dkb/zig/blob/master/lib/std/compress/testdata/rfc8478.txt Represents the 2-byte bitstream generated from the Huffman encoding of '0145'. This shows the raw bit sequence before and after symbolic separation. ```text 00010000 00001101 ``` ```text 0001_0000 00001_1_01 ``` -------------------------------- ### Zig Testing Framework Examples Source: https://context7.com/dkb/zig/llms.txt Demonstrates various assertion types available in Zig's testing module, including equality, error expectations, slice comparison, string comparison, and approximate floating-point equality. ```zig const std = @import("std"); const testing = std.testing; fn add(a: i32, b: i32) i32 { return a + b; } test "basic addition" { try testing.expectEqual(@as(i32, 5), add(2, 3)); } test "expect error" { const result = error.SomeError; try testing.expectError(error.SomeError, @as(anyerror!void, result)); } test "expect equal slices" { const expected = "hello"; const actual = "hello"; try testing.expectEqualSlices(u8, expected, actual); } test "expect strings" { try testing.expectEqualStrings("hello", "hello"); } test "approximate equality for floats" { try testing.expectApproxEqAbs(@as(f32, 1.0), @as(f32, 1.001), 0.01); } ``` -------------------------------- ### Zig Arena Allocator Example Source: https://context7.com/dkb/zig/llms.txt Demonstrates the ArenaAllocator for managing multiple allocations that are freed together upon deinitialization. Uses the page allocator as a backend. ```zig const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const testing = std.testing; test "arena allocator" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); // Multiple allocations - all freed at once with arena.deinit() const a = try allocator.alloc(u8, 100); const b = try allocator.alloc(i32, 50); _ = a; _ = b; // No need to free individual allocations } ``` -------------------------------- ### Build LLVM/Clang in Debug Mode (Windows) Source: https://github.com/dkb/zig/blob/master/README.md These commands are for building a debug version of LLVM and Clang on Windows. Note the different installation paths and build type. ```bat mkdir C:\Users\Andy\clang-21.0.0.src\build-debug cd C:\Users\Andy\clang-21.0.0.src\build-debug "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:\Users\andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-debug -DCMAKE_PREFIX_PATH=C:\Users\andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-debug -DCMAKE_BUILD_TYPE=Debug -DLLVM_USE_CRT_DEBUG=MTd msbuild /m INSTALL.vcxproj ``` -------------------------------- ### Configure and Build LLD (Debug Mode) Source: https://github.com/dkb/zig/blob/master/README.md Configures and builds the LLD linker in debug mode. This command sets installation and prefix paths, and specifies debug runtime libraries. ```bat mkdir C:\Users\Andy\lld-21.0.0.src\build-debug cd C:\Users\Andy\lld-21.0.0.src\build-debug "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:\Users\andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-debug -DCMAKE_PREFIX_PATH=C:\Users\andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-debug -DCMAKE_BUILD_TYPE=Debug -DLLVM_USE_CRT_DEBUG=MTd msbuild /m INSTALL.vcxproj ``` -------------------------------- ### Build LLVM/Clang in Release Mode (POSIX) Source: https://github.com/dkb/zig/blob/master/README.md Compile LLVM and Clang in release mode on POSIX systems using CMake and Ninja. This installs to a user-defined prefix. ```sh cd ~/Downloads git clone --depth 1 --branch release/21.x https://github.com/llvm/llvm-project llvm-project-21 cd llvm-project-21 git checkout release/21.x mkdir build-release cd build-release cmake ../llvm \ -DCMAKE_INSTALL_PREFIX=$HOME/local/llvm21-assert \ -DCMAKE_BUILD_TYPE=Release \ -DLLVM_ENABLE_PROJECTS="lld;clang" \ -DLLVM_ENABLE_LIBXML2=OFF \ -DLLVM_ENABLE_TERMINFO=OFF \ -DLLVM_ENABLE_LIBEDIT=OFF \ -DLLVM_ENABLE_ASSERTIONS=ON \ -DLLVM_PARALLEL_LINK_JOBS=1 \ -G Ninja ninja install ``` -------------------------------- ### Zig Test Backend and Target Configuration Source: https://github.com/dkb/zig/blob/master/test/cases/README.md Configure the test runner to use specific backends and targets. This example specifies 'selfhosted' and 'llvm' backends, and 'x86_64-linux' and 'x86_64-macos' targets. ```zig // run // backend=selfhosted,llvm // target=x86_64-linux,x86_64-macos ``` -------------------------------- ### Zig ArrayList Usage Example Source: https://context7.com/dkb/zig/llms.txt Demonstrates the usage of ArrayList for dynamic array operations like appending, slicing, and popping elements. Requires the testing allocator. ```zig const std = @import("std"); const ArrayList = std.ArrayList; const testing = std.testing; test "ArrayList usage" { var list = ArrayList(i32).init(testing.allocator); defer list.deinit(); // Append items try list.append(42); try list.append(100); try list.appendSlice(&[_]i32{ 1, 2, 3 }); try testing.expectEqual(@as(usize, 5), list.items.len); try testing.expectEqual(@as(i32, 42), list.items[0]); // Pop item const popped = list.pop(); try testing.expectEqual(@as(i32, 3), popped); // Convert to owned slice const owned = try list.toOwnedSlice(); defer testing.allocator.free(owned); try testing.expectEqual(@as(usize, 4), owned.len); } ``` -------------------------------- ### Build LLDB Fork with Zig Support Source: https://github.com/dkb/zig/blob/master/README.md Use these CMake commands to build the LLDB fork with Zig support. Ensure prerequisites are installed and consider configuring optional dependencies if CMake cannot find them. ```sh cmake llvm -G Ninja -B build -DLLVM_ENABLE_PROJECTS="clang;lldb" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLLVM_ENABLE_ASSERTIONS=ON -DLLDB_ENABLE_LIBEDIT=ON -DLLDB_ENABLE_PYTHON=ON cmake --build build --target lldb --target lldb-server ``` -------------------------------- ### Example Huffman Prefix Codes Source: https://github.com/dkb/zig/blob/master/lib/std/compress/testdata/rfc8478.txt Illustrates the distribution of prefix codes based on literal weights. This table shows the final prefix codes assigned to each literal after sorting by weight and then sequential order. ```text +---------+--------+----------------+--------------+ | Literal | Weight | Number_Of_Bits | Prefix Codes | +---------+--------+----------------|--------------+ | 3 | 0 | 0 | N/A | +---------+--------+----------------|--------------+ | 4 | 1 | 4 | 0000 | +---------+--------+----------------|--------------+ | 5 | 1 | 4 | 0001 | +---------+--------+----------------|--------------+ | 2 | 2 | 3 | 001 | +---------+--------+----------------|--------------+ | 1 | 3 | 2 | 01 | +---------+--------+----------------|--------------+ | 0 | 4 | 1 | 1 | +---------+--------+----------------|--------------+ ``` -------------------------------- ### Build Zig from Source Using Prebuilt Zig Source: https://github.com/dkb/zig/blob/master/README.md Build Zig using a prior Zig build and LLVM libraries. Requires setting ZIG_PREFIX and LLVM_PREFIX environment variables or providing paths directly. Use '-Dstatic-llvm' for static LLVM linking. ```sh "$ZIG_PREFIX/zig" build \ -p stage3 \ --search-prefix "$LLVM_PREFIX" \ --zig-lib-dir "lib" \ -Dstatic-llvm ``` -------------------------------- ### Zig Hello World Program Source: https://context7.com/dkb/zig/llms.txt The standard entry point for a Zig program that prints 'Hello, World!' to the console. Requires standard library import. ```zig const std = @import("std"); pub fn main(init: std.process.Init) !void { try std.Io.File.stdout().writeStreamingAll(init.io, "Hello, World!\n"); } ``` -------------------------------- ### Zig Build System Configuration Source: https://context7.com/dkb/zig/llms.txt Shows a basic Zig build script (`build.zig`) for creating an executable, linking system libraries, and defining run/test steps. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { // Standard target options const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // Add executable const exe = b.addExecutable(.{ .name = "myapp", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); // Link system library exe.linkSystemLibrary("c"); // Install artifact b.installArtifact(exe); // Add run step const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_cmd.step); // Add test step const unit_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }), }); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&b.addRunArtifact(unit_tests).step); } ``` -------------------------------- ### Build with Zig build system Source: https://github.com/dkb/zig/blob/master/README.md Build the project using the Zig build system, specifying the output path, search prefix for dependencies, Zig library directory, and target architecture. The `-Dstatic-llvm` flag is used to link LLVM statically. ```bat $DEVKIT\bin\zig.exe build -p stage3 --search-prefix $DEVKIT --zig-lib-dir lib -Dstatic-llvm -Duse-zig-libcxx -Dtarget=x86_64-windows-gnu ``` -------------------------------- ### Serve Standard Library Autodocs Source: https://github.com/dkb/zig/blob/master/README.md The `zig std` command spawns an HTTP server to provide Autodoc assets for the standard library on the fly, allowing for immediate reflection of source changes. ```zig zig std ``` -------------------------------- ### Run Standard Library Tests with Native Target Source: https://github.com/dkb/zig/blob/master/README.md Executes the standard library tests using only the native target configuration. This is estimated to complete in 3 minutes. ```bash zig build test-std -Dno-matrix ``` -------------------------------- ### Build LLVM/Clang in Release Mode (Windows) Source: https://github.com/dkb/zig/blob/master/README.md Use these commands to create a release build of LLVM and Clang on Windows. Ensure CMake and MSBuild are in your PATH. ```bat mkdir C:\Users\Andy\clang-21.0.0.src\build-release cd C:\Users\Andy\clang-21.0.0.src\build-release "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:\Users\Andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-release-mt -DCMAKE_PREFIX_PATH=C:\Users\Andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-release-mt -DCMAKE_BUILD_TYPE=Release -DLLVM_USE_CRT_RELEASE=MT msbuild /m -p:Configuration=Release INSTALL.vcxproj ``` -------------------------------- ### Configure LLDB Pretty Printers for Zig Source: https://github.com/dkb/zig/blob/master/README.md Add these commands to your `~/.lldbinit` file to enable pretty printers for debugging Zig code. The specific commands depend on whether you are debugging Zig code compiled with Zig's LLVM backend. ```lldb command script import /path/to/zig/tools/lldb_pretty_printers.py ``` ```lldb type category enable zig.lang ``` ```lldb type category enable zig.std ``` ```lldb type category enable zig.stage2 ``` -------------------------------- ### Define Build Arguments for zig2 Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Sets up arguments for building the 'zig2' executable, specifying source directories, build options, and dependencies. ```cmake set(BUILD_ZIG2_ARGS "${PROJECT_SOURCE_DIR}/lib" build-exe -ofmt=c -lc -OReleaseSmall --name zig2 -femit-bin="${ZIG2_C_SOURCE}" -target "${ZIG_HOST_TARGET_TRIPLE}" --dep "build_options" --dep "aro" "-Mroot=src/main.zig" "-Mbuild_options=${ZIG_CONFIG_ZIG_OUT}" "-Maro=lib/compiler/aro/aro.zig" ) ``` -------------------------------- ### Zig Generic List Structure Source: https://context7.com/dkb/zig/llms.txt Defines a generic `List` type using `comptime` that can hold items of any specified type `T`. Includes a `get` method for accessing items. ```zig // Generic data structure fn List(comptime T: type) type { return struct { items: []T, len: usize, const Self = @This(); pub fn get(self: Self, index: usize) T { return self.items[index]; } }; } test "generic list" { var buffer: [10]i32 = undefined; var list = List(i32){ .items = &buffer, .len = 0, }; _ = list; } ``` -------------------------------- ### Test Standard Library from Build Subdirectory Source: https://github.com/dkb/zig/blob/master/README.md If using `-Dno-lib` and operating from a `build/` subdirectory, the `--zig-lib-dir` argument can be omitted when directly testing the standard library. ```bash stage3/bin/zig test ../lib/std/std.zig ``` -------------------------------- ### Zig Sorting Algorithms Source: https://context7.com/dkb/zig/llms.txt Shows how to use `std.sort.insertion` and `std.sort.heap` for sorting slices. Requires a `lessThan` comparison function. ```zig const std = @import("std"); const sort = std.sort; const testing = std.testing; test "sorting slices" { var items = [_]i32{ 5, 3, 8, 1, 9, 2 }; // Sort using insertion sort (stable, good for small arrays) sort.insertion(i32, &items, {}, struct { fn lessThan(_: void, a: i32, b: i32) bool { return a < b; } }.lessThan); try testing.expectEqual([_]i32{ 1, 2, 3, 5, 8, 9 }, items); } ``` ```zig const std = @import("std"); const sort = std.sort; const testing = std.testing; test "heap sort" { var items = [_]i32{ 5, 3, 8, 1, 9, 2 }; sort.heap(i32, &items, {}, struct { fn lessThan(_: void, a: i32, b: i32) bool { return a < b; } }.lessThan); try testing.expectEqual([_]i32{ 1, 2, 3, 5, 8, 9 }, items); } ``` -------------------------------- ### Directly Test Standard Library with `zig test` Source: https://github.com/dkb/zig/blob/master/README.md Use `zig test` directly to run standard library tests from the repository root. Specify `--zig-lib-dir` if not in a `build/` subdirectory. ```bash zig test lib/std/std.zig --zig-lib-dir lib ``` -------------------------------- ### Configure CMake with Zig Dev Kit Source: https://github.com/dkb/zig/blob/master/README.md Configure the build using CMake, specifying the development kit path and Zig compilers. Ensure to use forward slashes for paths. The `-DZIG_STATIC=ON` flag is used for static builds. ```bat cmake .. -GNinja -DCMAKE_PREFIX_PATH="%DEVKIT%" -DCMAKE_C_COMPILER="%DEVKIT%/bin/zig.exe;cc" -DCMAKE_CXX_COMPILER="%DEVKIT%/bin/zig.exe;c++" -DCMAKE_AR="%DEVKIT%/bin/zig.exe" -DZIG_AR_WORKAROUND=ON -DZIG_STATIC=ON -DZIG_USE_LLVM_CONFIG=OFF ``` -------------------------------- ### Direct Weight Encoding Example Source: https://github.com/dkb/zig/blob/master/lib/std/compress/testdata/rfc8478.txt Illustrates how weights are encoded directly as 4-bit fields within bytes when headerByte is 128 or greater. The first weight uses the top 4 bits, and the second uses the bottom 4 bits of a byte. ```pseudocode Weight[0] = (Byte[0] >> 4) Weight[1] = (Byte[0] & 0xf), ``` -------------------------------- ### Define Zig Build Arguments Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Sets up common arguments for the Zig build process, including library directory, version string, target architecture, and optimization flags based on CMAKE_BUILD_TYPE. ```cmake set(ZIG_BUILD_ARGS --zig-lib-dir "${PROJECT_SOURCE_DIR}/lib" "-Dversion-string=${RESOLVED_ZIG_VERSION}" "-Dtarget=${ZIG_TARGET_TRIPLE}" "-Dcpu=${ZIG_TARGET_MCPU}" -Denable-llvm "-Dconfig_h=${ZIG_CONFIG_H_OUT}" ) set(ZIG_EXTRA_BUILD_ARGS "" CACHE STRING "Extra zig build args") if(ZIG_EXTRA_BUILD_ARGS) list(APPEND ZIG_BUILD_ARGS ${ZIG_EXTRA_BUILD_ARGS}) endif() set(ZIG_RELEASE_SAFE OFF CACHE BOOL "Build Zig as ReleaseSafe (with debug assertions on)") if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") list(APPEND ZIG_BUILD_ARGS -Doptimize=Debug) else() if("${CMAKE_BUILD_TYPE}" STREQUAL "MinSizeRel") list(APPEND ZIG_BUILD_ARGS -Doptimize=ReleaseSmall) else() # Release and RelWithDebInfo if(ZIG_RELEASE_SAFE) list(APPEND ZIG_BUILD_ARGS -Doptimize=ReleaseSafe) else() list(APPEND ZIG_BUILD_ARGS -Doptimize=ReleaseFast) endif() if(NOT "${CMAKE_BUILD_TYPE}" STREQUAL "RelWithDebInfo") list(APPEND ZIG_BUILD_ARGS -Dstrip) endif() endif() endif() if(ZIG_STATIC AND NOT MSVC) list(APPEND ZIG_BUILD_ARGS -Duse-zig-libcxx) endif() if(ZIG_NO_LIB) list(APPEND ZIG_BUILD_ARGS -Dno-lib) endif() if(ZIG_SINGLE_THREADED) list(APPEND ZIG_BUILD_ARGS -Dsingle-threaded) endif() if(ZIG_PIE) list(APPEND ZIG_BUILD_ARGS -Dpie) endif() if(NOT "${ZIG_TARGET_DYNAMIC_LINKER}" STREQUAL "") list(APPEND ZIG_BUILD_ARGS "-Ddynamic-linker=${ZIG_TARGET_DYNAMIC_LINKER}") endif() ``` -------------------------------- ### Zig I/O System Overview Source: https://context7.com/dkb/zig/llms.txt Outlines the capabilities of Zig's `std.Io` module, which provides a cross-platform interface for file system, networking, processes, time, and asynchronous operations. ```zig const std = @import("std"); const Io = std.Io; // Io provides: // - File system operations (Dir, File) // - Networking (net module) // - Process management // - Time and sleeping // - Async/await concurrency // - Mutexes, semaphores, RwLocks // File operations through Io.File // Directory operations through Io.Dir // Network operations through Io.net // Reader/Writer abstractions through Io.Reader, Io.Writer ``` -------------------------------- ### Zig Memory Utilities Test Source: https://context7.com/dkb/zig/llms.txt Demonstrates various memory utility functions in Zig, including slice comparison, substring search, string splitting, and zero initialization. Ensure the 'std' and 'testing' modules are imported. ```zig const std = @import("std"); const mem = std.mem; const testing = std.testing; test "memory utilities" { // Compare slices try testing.expect(mem.eql(u8, "hello", "hello")); try testing.expect(!mem.eql(u8, "hello", "world")); // Find in slice const index = mem.indexOf(u8, "hello world", "world"); try testing.expectEqual(@as(?usize, 6), index); // Split string var iter = mem.splitSequence(u8, "a,b,c", ","); try testing.expectEqualStrings("a", iter.next().?); try testing.expectEqualStrings("b", iter.next().?); try testing.expectEqualStrings("c", iter.next().?); // Zero initialize const zeroed = mem.zeroes([4]u8); try testing.expectEqual([_]u8{ 0, 0, 0, 0 }, zeroed); } ``` -------------------------------- ### Define Build Arguments for Compiler Runtime Object Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Sets up arguments for building the compiler runtime object file, specifying output format, optimization level, and target. ```cmake set(BUILD_COMPILER_RT_ARGS "${PROJECT_SOURCE_DIR}/lib" build-obj -ofmt=c -OReleaseSmall --name compiler_rt -femit-bin="${ZIG_COMPILER_RT_C_SOURCE}" -target "${ZIG_HOST_TARGET_TRIPLE}" "-Mroot=lib/compiler_rt.zig" ) ``` -------------------------------- ### Configure and Build LLVM (Release Mode) Source: https://github.com/dkb/zig/blob/master/README.md Configures and builds LLVM in release mode using CMake and MSBuild. Ensure CMake is in your PATH and the correct Visual Studio version is selected. ```bat mkdir C:\Users\Andy\llvm-21.0.0.src\build-release cd C:\Users\Andy\llvm-21.0.0.src\build-release "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_INSTALL_PREFIX=C:\Users\Andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-release-mt -DCMAKE_PREFIX_PATH=C:\Users\Andy\llvm+clang+lld-21.0.0-x86_64-windows-msvc-release-mt - DLLVM_ENABLE_ZLIB=OFF -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_LIBXML2=OFF -DLLVM_USE_CRT_RELEASE=MT msbuild /m -p:Configuration=Release INSTALL.vcxproj ``` -------------------------------- ### Zig Thread Spawning Source: https://context7.com/dkb/zig/llms.txt Demonstrates creating and managing threads using `std.Thread.spawn`. Ensure threads are joined to wait for completion. ```zig const std = @import("std"); const Thread = std.Thread; const testing = std.testing; fn threadFunction(data: *i32) void { data.* += 1; } test "spawn thread" { var data: i32 = 0; const thread = try Thread.spawn(.{}, threadFunction, .{&data}); thread.join(); try testing.expectEqual(@as(i32, 1), data); } ``` -------------------------------- ### Run Zig tests Source: https://github.com/dkb/zig/blob/master/README.md Execute the test suite for the Zig build using the newly compiled zig.exe. ```bat bin\zig.exe build test ``` -------------------------------- ### Configure Zig Build System Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Configures the build system by copying input files to their output locations. This is typically used for generating configuration headers. ```cmake configure_file ( stage1/config.h.in "${ZIG_CONFIG_H_OUT}" ) configure_file ( stage1/config.zig.in "${ZIG_CONFIG_ZIG_OUT}" ) ``` -------------------------------- ### Build Zig from Source without LLVM Source: https://github.com/dkb/zig/blob/master/README.md Build Zig using only a C compiler, resulting in a 'stage2' build without LLVM extensions. This method has limitations on optimizations and linking features. ```sh cc -o bootstrap bootstrap.c ./bootstrap ``` ```sh ./zig2 build ``` -------------------------------- ### Zig Basic Memory Allocation Source: https://context7.com/dkb/zig/llms.txt Shows fundamental memory allocation and deallocation using the testing allocator. Includes allocation, freeing, and resizing. ```zig const std = @import("std"); const mem = std.mem; const Allocator = mem.Allocator; const testing = std.testing; test "allocator basics" { // Allocate memory const slice = try testing.allocator.alloc(u8, 100); defer testing.allocator.free(slice); // Fill with a pattern @memset(slice, 0xAA); try testing.expectEqual(@as(u8, 0xAA), slice[0]); // Resize if possible if (testing.allocator.resize(slice, 200)) { // Successfully resized in-place } } ``` -------------------------------- ### Configure CMake for Visual Studio Build Source: https://github.com/dkb/zig/blob/master/README.md Configure the build using CMake for Visual Studio, specifying the host and target architecture, generator, and the prefix path to the LLVM/Clang/LLD build. Ensure no trailing slash on CMAKE_PREFIX_PATH. ```bat "c:\Program Files\CMake\bin\cmake.exe" .. -Thost=x64 -G "Visual Studio 16 2019" -A x64 -DCMAKE_PREFIX_PATH=C:\Users\Andy\llvm+clang+lld-20.0.0-x86_64-windows-msvc-release-mt -DCMAKE_BUILD_TYPE=Release ``` -------------------------------- ### Initialize Zig Prefix Path Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Appends CMAKE_PREFIX_PATH and environment variable CMAKE_PREFIX_PATH to ZIG_CMAKE_PREFIX_PATH, handling Windows and non-Windows environments differently. ```cmake list(APPEND ZIG_CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH}") if(WIN32) list(APPEND ZIG_CMAKE_PREFIX_PATH $ENV{CMAKE_PREFIX_PATH}) else() string(REGEX REPLACE ":" ";" ZIG_CMAKE_PREFIX_PATH_STRING "$ENV{CMAKE_PREFIX_PATH}") list(APPEND ZIG_CMAKE_PREFIX_PATH "${ZIG_CMAKE_PREFIX_PATH_STRING}") endif() ``` -------------------------------- ### Generate zig1.c from WASM Module Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Configures a custom command to run `zig-wasm2c` to convert the `zig1.wasm` module into a C source file (`zig1.c`). This is a build-time generation step. ```cmake add_custom_command( OUTPUT "${ZIG1_C_SOURCE}" COMMAND zig-wasm2c "${ZIG1_WASM_MODULE}" "${ZIG1_C_SOURCE}" DEPENDS zig-wasm2c "${ZIG1_WASM_MODULE}" COMMENT "Converting ${ZIG1_WASM_MODULE} to ${ZIG1_C_SOURCE}" WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" ) ``` -------------------------------- ### Link Libraries and Options for zig1 Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Configures linking for the `zig1` executable, adding the math library (`m`) for non-MSVC targets and setting stack size options for MinGW. ```cmake if(MSVC) target_link_options(zig1 PRIVATE /STACK:0x10000000) else() target_link_libraries(zig1 LINK_PUBLIC m) if(MINGW) target_link_options(zig1 PRIVATE -Wl,--stack,0x10000000) endif() endif() ``` -------------------------------- ### Zig Compression Module Usage Source: https://context7.com/dkb/zig/llms.txt Illustrates the availability of various compression algorithms within the Zig standard library's `std.compress` module. This snippet primarily serves as a placeholder to show module import. ```zig const std = @import("std"); const compress = std.compress; const testing = std.testing; test "gzip decompression" { // compress.flate provides gzip and zlib functionality // compress.zstd provides Zstandard compression // compress.lzma provides LZMA compression // compress.xz provides XZ compression _ = compress.flate; _ = compress.zstd; _ = compress.lzma; _ = compress.xz; } ``` -------------------------------- ### Zig Defer and Errdefer for Resource Management Source: https://context7.com/dkb/zig/llms.txt Illustrates `defer` for scope exit cleanup and `errdefer` for error-specific cleanup. `defer` executes in reverse order of declaration. ```zig const std = @import("std"); const Allocator = std.mem.Allocator; fn createResource(allocator: Allocator) ![]u8 { const resource = try allocator.alloc(u8, 100); errdefer allocator.free(resource); // Only runs if error returned // Simulate some operation that might fail if (resource.len < 50) { return error.ResourceTooSmall; } return resource; } test "defer ordering" { var order: [3]u8 = undefined; var i: usize = 0; { defer { order[i] = 1; i += 1; } defer { order[i] = 2; i += 1; } defer { order[i] = 3; i += 1; } } // Defers run in reverse order try std.testing.expectEqual([_]u8{ 3, 2, 1 }, order); } ``` -------------------------------- ### Custom Command to Generate Compiler Runtime C Source Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Defines a custom command to run 'zig1.wasm' to produce the C source file for the compiler runtime. Ensures dependencies are met. ```cmake add_custom_command( OUTPUT "${ZIG_COMPILER_RT_C_SOURCE}" COMMAND zig1 ${BUILD_COMPILER_RT_ARGS} DEPENDS zig1 "${ZIG_STAGE2_SOURCES}" COMMENT "Running zig1.wasm to produce ${ZIG_COMPILER_RT_C_SOURCE}" WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" ) ``` -------------------------------- ### Custom Command to Generate zig2 C Source Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Defines a custom command to run 'zig1.wasm' to produce the C source file for 'zig2'. Ensures dependencies are met. ```cmake add_custom_command( OUTPUT "${ZIG2_C_SOURCE}" COMMAND zig1 ${BUILD_ZIG2_ARGS} DEPENDS zig1 "${ZIG_STAGE2_SOURCES}" COMMENT "Running zig1.wasm to produce ${ZIG2_C_SOURCE}" WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}" ) ``` -------------------------------- ### Configure Target and Linker Options Source: https://github.com/dkb/zig/blob/master/CMakeLists.txt Sets cache variables for the target triple, target CPU, and an optional dynamic linker override. It also determines whether to use `llvm-config` based on the target triple. ```cmake set(ZIG_TARGET_TRIPLE "native" CACHE STRING "arch-os-abi to output binaries for") set(ZIG_TARGET_MCPU "native" CACHE STRING "-mcpu parameter to output binaries for") set(ZIG_TARGET_DYNAMIC_LINKER "" CACHE STRING "Override the dynamic linker used by the Zig binary. Default is to auto-detect the dynamic linker.") set(ZIG_SINGLE_THREADED off CACHE BOOL "limit the zig compiler to use only 1 thread") set(ZIG_AR_WORKAROUND off CACHE BOOL "append 'ar' subcommand to CMAKE_AR") if("${ZIG_TARGET_TRIPLE}" STREQUAL "native") set(ZIG_USE_LLVM_CONFIG ON CACHE BOOL "use llvm-config to find LLVM libraries") else() set(ZIG_USE_LLVM_CONFIG OFF CACHE BOOL "use llvm-config to find LLVM libraries") endif() ``` -------------------------------- ### Zig HTTP Client Configuration Source: https://context7.com/dkb/zig/llms.txt Provides an overview of the Zig HTTP client's components, including configuration, available HTTP methods, and status codes. ```zig const std = @import("std"); const http = std.http; // HTTP Client configuration const Client = http.Client; // HTTP methods available const Method = http.Method; // .GET, .POST, .PUT, .DELETE, .PATCH, .HEAD, .OPTIONS, .CONNECT, .TRACE // HTTP status codes const Status = http.Status; // .ok (200), .created (201), .not_found (404), .internal_server_error (500), etc. ``` -------------------------------- ### Build Zig from Source After Local Changes Source: https://github.com/dkb/zig/blob/master/README.md Build Zig from source after making local modifications. This command uses a debug build configuration for testing. ```bash stage3/bin/zig build -p stage4 -Denable-llvm -Dno-lib ```