### Rendering Zig Book with Quarto (Manual Build) Source: https://github.com/pedropark99/zig-book/blob/main/README.md This command initiates the Quarto publishing system to compile and render the Zig book. It generates the HTML content, internal links, and chapter structure, assuming Quarto is correctly installed and configured on the system. ```bash quarto render ``` -------------------------------- ### Installing R Packages for Zig Book Source: https://github.com/pedropark99/zig-book/blob/main/README.md This command executes the `dependencies.R` R script to install all necessary R packages required for building the Zig book. It's a prerequisite step after manually installing Zig, R, and Quarto, ensuring all R-related tools like `knitr` and `rmarkdown` are available. ```bash Rscript dependencies.R ``` -------------------------------- ### Entering Nix Development Environment for Zig Book Source: https://github.com/pedropark99/zig-book/blob/main/README.md This command uses Nix Flake to create a reproducible development environment for the Zig book project. It downloads required packages and libraries, then opens a new bash session with these dependencies pre-installed, facilitating the book's build process without manual setup. ```bash nix develop ``` -------------------------------- ### Defining and Installing an Executable in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This Zig build script snippet defines an executable target named 'hello' using `b.addExecutable`, specifying its source file and target. Crucially, `b.installArtifact(exe)` is then called to copy the built executable into the `zig-out` directory, making it available after the build completes. Without this explicit installation, the artifact would be discarded. ```Zig const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.host, }); b.installArtifact(exe); ``` -------------------------------- ### Building a Zig Project Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/13-image-filter.html This command is used to initiate the build process for a Zig project. It relies on the project's `build.zig` file to define the compilation and linking steps. A prerequisite for this specific project is the installation of `libspng` on the system. ```Zig zig build ``` -------------------------------- ### Starting LLDB with a Program Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html This command launches the LLDB debugger and loads the specified executable 'add_program'. This is the initial step to begin an interactive debugging session. ```Shell lldb add_program ``` -------------------------------- ### Example Relative File Path Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/12-file-op.html This snippet illustrates a relative path used to locate the 'hello_world.zig' file. Relative paths are resolved starting from the current working directory (CWD) of the executing program, providing a flexible way to reference files without specifying the full absolute location. ```File System Path ZigExamples/zig-basics/hello_world.zig ``` -------------------------------- ### Handling HTTP GET Requests in Zig Main Function Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This `main` function in Zig sets up a basic HTTP server, accepts a client connection, reads and parses the incoming HTTP request. It then conditionally calls `Response.send_200` if the request method is GET and the URI is "/", otherwise it calls `Response.send_404`. This demonstrates basic request routing based on URI and method. ```Zig const std = @import("std"); const SocketConf = @import("config.zig"); const Request = @import("request.zig"); const Response = @import("response.zig"); const Method = Request.Method; const stdout = std.io.getStdOut().writer(); pub fn main() !void { const socket = try SocketConf.Socket.init(); try stdout.print("Server Addr: {any}\n", .{socket._address}); var server = try socket._address.listen(.{}); const connection = try server.accept(); var buffer: [1000]u8 = undefined; for (0..buffer.len) |i| { buffer[i] = 0; } try Request.read_request(connection, buffer[0..buffer.len]); const request = Request.parse_request( buffer[0..buffer.len] ); if (request.method == Method.GET) { if (std.mem.eql(u8, request.uri, "/")) { try Response.send_200(connection); } else { try Response.send_404(connection); } } } ``` -------------------------------- ### Example HTTP GET Request Top-Level Header Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This snippet illustrates the top-level header of an HTTP GET request. It specifies the HTTP method (GET), the URI endpoint (/users/list) for resource access, and the HTTP protocol version (HTTP/1.1). This line is crucial for initiating communication with a server. ```HTTP Request GET /users/list HTTP/1.1 ``` -------------------------------- ### Rendering Zig Book within Nix Environment Source: https://github.com/pedropark99/zig-book/blob/main/README.md After entering the Nix development environment, this command renders the Zig book using Quarto. It leverages the pre-configured dependencies within the Nix shell to build the book's HTML content and structure, ensuring a consistent build process. ```bash quarto render ``` -------------------------------- ### Example Zig Program for Debugging Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html This Zig program defines an 'add_and_increment' function and a 'main' function that calls it multiple times. It serves as the target for the debugging demonstration, showcasing basic arithmetic operations and standard output. ```Zig const std = @import("std"); const stdout = std.io.getStdOut().writer(); fn add_and_increment(a: u8, b: u8) u8 { const sum = a + b; const incremented = sum + 1; return incremented; } pub fn main() !void { var n = add_and_increment(2, 3); n = add_and_increment(n, n); try stdout.print("Result: {d}!\n", .{n}); } ``` -------------------------------- ### Adding an Executable with Optimization (Zig) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This snippet demonstrates how to add a new executable target to a Zig build script. It specifies the executable's name, source file, target platform, and sets the optimization level to `ReleaseSafe` for safe release builds. Finally, it installs the created artifact. ```Zig const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.host, .optimize = .ReleaseSafe }); b.installArtifact(exe); ``` -------------------------------- ### Setting Breakpoint and Running in LLDB Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html These LLDB commands set a breakpoint at the 'main' function and then start the program's execution. The program will pause at the beginning of the 'main' function, allowing for inspection. ```LLDB (lldb) b main (lldb) run ``` -------------------------------- ### Creating a Run Artifact for Executable (Zig) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This code demonstrates how to create a "run artifact" in a Zig build script. After defining and installing an executable, `b.addRunArtifact(exe)` is used to create an artifact capable of executing the specified binary, enabling a combined build and run process. ```Zig const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("src/hello.zig"), .target = b.host }); b.installArtifact(exe); const run_arti = b.addRunArtifact(exe); ``` -------------------------------- ### Linking System Libraries in Zig Build Script Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This snippet demonstrates how to configure a Zig executable to link against system libraries. It shows the use of `linkLibC()` to link with the C Standard Library and `linkSystemLibrary("png")` to link with the `libpng` system library, ensuring the executable `image_filter` can use their functionalities. It also installs the artifact. ```Zig const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "image_filter", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.linkLibC(); exe.linkSystemLibrary("png"); b.installArtifact(exe); } ``` -------------------------------- ### Setting User-Provided Build Options via CLI in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This command-line example demonstrates how to pass a value to a user-defined build option (`use_zlib`) when invoking the `zig build` command. The `-D` prefix is used to specify the option name and its desired value, enabling dynamic configuration of the build process. ```Shell zig build -Duse_zlib=false ``` -------------------------------- ### Initializing a New Zig Project Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This snippet demonstrates the command-line steps required to create a new directory, navigate into it, and initialize a basic Zig project structure using the 'zig init' command. This command sets up the necessary files for a new Zig application. ```Shell mkdir hello_world cd hello_world zig init ``` -------------------------------- ### Slicing an Array from a Specific Index to the End in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This example shows how to create a slice that starts at a specified index and extends to the very last element of the array. The `start..` syntax tells the Zig compiler to include all elements from the `start` index (here, index 1) until the end of the `ns` array. The `_ = sl;` line prevents unused variable warnings. ```Zig const ns = [4]u8{48, 24, 12, 6}; const sl = ns[1..]; _ = sl; ``` -------------------------------- ### Creating a Slice with Inclusive Start and Exclusive End in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This example illustrates creating a slice from an array using the `start..end` range selector. The slice `sl` will contain elements from index 1 up to, but not including, index 3 (i.e., elements at index 1 and 2). The `_ = sl;` line is used to acknowledge the variable and prevent unused variable warnings. ```Zig const ns = [4]u8{48, 24, 12, 6}; const sl = ns[1..3]; _ = sl; ``` -------------------------------- ### Registering a Build Step to Run Unit Tests in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This Zig code demonstrates how to create a new build step named 'tests' that executes the previously defined unit test executable. By using `b.addRunArtifact()` and `b.step()`, this allows users to run all unit tests with a single command-line instruction, simplifying the testing workflow. ```Zig const run_arti = b.addRunArtifact(test_exe); const run_step = b.step("tests", "Run unit tests"); run_step.dependOn(&run_arti.step); ``` -------------------------------- ### Example Parsed HTTP Request Object in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This snippet shows an example of the `Request` object's structure after being parsed by the `parse_request` function. It illustrates how method, version (as byte array), and URI (as byte array) are represented, highlighting Zig's `any` format specifier output for byte sequences. ```Zig request.Request{ .method = request.Method.GET, .version = {72, 84, 84, 80, 47, 49, 46, 49, 13}, .uri = {47} } ``` -------------------------------- ### Viewing Available Build Steps (CLI) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This command-line snippet shows how to view the available steps in a Zig build script. Running `zig build --help` in the terminal displays a list of defined steps, including any custom ones like "run" that have been added to the build script. ```Shell zig build --help ``` -------------------------------- ### Viewing Initial Zig Project Structure Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This snippet displays the default file and directory structure generated by the `zig init` command using the `tree` utility. It shows the `build.zig` and `build.zig.zon` files at the root, and the `main.zig` and `root.zig` source files nested within the `src` directory. This structure is fundamental for understanding how Zig projects are organized. ```Shell .\n├── build.zig\n├── build.zig.zon\n└── src\n ├── main.zig\n └── root.zig\n\n1 directory, 4 files ``` -------------------------------- ### Initializing libspng Context and Opening PNG File in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/13-image-filter.html This snippet demonstrates how to import necessary C headers (`stdio.h`, `spng.h`) into a Zig project, open a PNG file using `fopen`, create a `libspng` context, and associate the opened file with the `libspng` context for subsequent operations. It handles potential file opening errors. ```Zig const c = @cImport({ @cDefine("_NO_CRT_STDIO_INLINE", "1"); @cInclude("stdio.h"); @cInclude("spng.h"); }); const path = "pedro_pascal.png"; const file_descriptor = c.fopen(path, "rb"); if (file_descriptor == null) { @panic("Could not open file!"); } const ctx = c.spng_ctx_new(0) orelse unreachable; _ = c.spng_set_png_file( ctx, @ptrCast(file_descriptor) ); ``` -------------------------------- ### Instantiating and Using a Generic u8 Stack in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/10-stack-project.html This example demonstrates how to instantiate and use the generic `Stack` for `u8` values. It initializes a `GeneralPurposeAllocator`, defines `Stacku8` by passing `u8` to the generic `Stack` function, creates a `stack` instance, pushes multiple `u8` values, and then prints its length and capacity before popping an element. The `defer stack.deinit()` ensures proper memory cleanup. ```Zig var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const Stacku8 = Stack(u8); var stack = try Stacku8.init(allocator, 10); defer stack.deinit(); try stack.push(1); try stack.push(2); try stack.push(3); try stack.push(4); try stack.push(5); try stack.push(6); std.debug.print("Stack len: {d}\n", .{stack.length}); std.debug.print("Stack capacity: {d}\n", .{stack.capacity}); stack.pop(); ``` -------------------------------- ### Detecting Code Annotations Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/03-unittests.html This utility function checks if a given DOM element has a class that starts with 'code-annotation-'. It is used to identify and filter out annotation elements from code blocks before copying their content. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Listening and Accepting Single Connection with Zig Socket Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This Zig code snippet demonstrates how to initialize a socket, make it listen for incoming connections, and accept a single client connection. It imports `std` for standard I/O and `config.zig` for the `Socket` struct. The `listen()` method creates a server object that waits for a connection, and `accept()` establishes that connection, after which the program concludes, serving only one client. ```Zig const std = @import("std"); const SocketConf = @import("config.zig"); const stdout = std.io.getStdOut().writer(); pub fn main() !void { const socket = try SocketConf.Socket.init(); try stdout.print("Server Addr: {any}\n", .{socket._address}); var server = try socket._address.listen(.{}); const connection = try server.accept(); _ = connection; } ``` -------------------------------- ### CSS Styling for Hanging Indent Source: https://github.com/pedropark99/zig-book/blob/main/docs/index.html This CSS rule creates a hanging indent effect for elements with the `hanging-indent` class, where the first line of text starts further left than subsequent lines. ```CSS div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;} ``` -------------------------------- ### Defining the `build()` Function in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This snippet illustrates the basic structure of a `build.zig` script in Zig. It imports the standard library (`std`) and defines the public `build` function, which serves as the entry point for the build process. This function accepts a pointer to a `std.Build` object, which is used to configure and execute build steps. ```Zig const std = @import("std"); pub fn build(b: *std.Build) void { ``` -------------------------------- ### Checking Alternate Color Scheme Sentinel in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This function checks if the 'alternate' color scheme is currently active by retrieving a sentinel value. It relies on `getColorSchemeSentinel()` to get the stored or default theme preference. ```JavaScript const hasAlternateSentinel = () => { let styleSentinel = getColorSchemeSentinel(); if (styleSentinel !== null) { return styleSentinel === "alternate"; } else { return false; } } ``` -------------------------------- ### Using Base64 encode and decode functions in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-base64.html This snippet demonstrates the practical usage of the `Base64` struct's `encode()` and `decode()` methods. It initializes a fixed-size memory buffer and an allocator, then encodes a sample string and decodes a Base64-encoded string, finally printing both the encoded and decoded results to standard output. ```Zig var memory_buffer: [1000]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init( &memory_buffer ); const allocator = fba.allocator(); const text = "Testing some more stuff"; const etext = "VGVzdGluZyBzb21lIG1vcmUgc3R1ZmY="; const base64 = Base64.init(); const encoded_text = try base64.encode( allocator, text ); const decoded_text = try base64.decode( allocator, etext ); try stdout.print( "Encoded text: {s}\n", .{encoded_text} ); try stdout.print( "Decoded text: {s}\n", .{decoded_text} ); ``` -------------------------------- ### Checking String Prefix with std.mem.startsWith in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This example illustrates the use of `std.mem.startsWith()` to check if a string begins with a specified substring. It requires the element type (`u8`), the main string, and the prefix string. The function returns a boolean value. ```Zig const name: []const u8 = "Pedro"; try stdout.print( "{any}\n", .{std.mem.startsWith(u8, name, "Pe")} ); ``` -------------------------------- ### Defining and Installing an Executable Target in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This snippet demonstrates how to define an executable target using `b.addExecutable()` within a Zig build script. It specifies the output `name`, the `root_source_file` for the project's entry point, and the `target` architecture, using `b.host` for the current machine. The `b.installArtifact()` function then ensures the compiled executable is placed in the build output directory. ```Zig const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .target = b.host, }); b.installArtifact(exe); ``` -------------------------------- ### Checking for Code Annotation Class - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/12-file-op.html This utility function checks if a given HTML element has any class that starts with 'code-annotation-'. It's primarily used to identify and filter out annotation elements when copying code snippets. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Executing Compiled Zig Binary Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This command executes the compiled Zig binary named `main` located in the current directory. It demonstrates the expected 'Hello, world!' output from the program. ```Shell ./main ``` ```Shell Hello, world! ``` -------------------------------- ### Checking for Code Annotation Class - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html Defines a utility function `isCodeAnnotation` that checks if an HTML element has any CSS class starting with 'code-annotation-'. This is used to identify and potentially remove specific annotations from code blocks before copying. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Identifying Code Annotation Elements in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This utility function checks if a given HTML element is a code annotation by iterating through its class list and looking for classes that start with 'code-annotation-'. This is used to exclude annotations when copying code. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Example Usage of Base64 Lookup Table in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-base64.html This Zig snippet demonstrates how to use the `Base64` struct. It first initializes a `Base64` object using `Base64.init()`. Then, it uses `stdout.print` to output the character found at index 28 in the Base64 lookup table, retrieved via the `_char_at()` method. This illustrates the efficiency of using a lookup table for character retrieval. ```Zig const base64 = Base64.init(); try stdout.print( "Character at index 28: {c}\n", .{base64._char_at(28)} ); ``` -------------------------------- ### Checking for Code Annotation Class - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html Defines a utility function `isCodeAnnotation` that checks if an HTML element has any CSS class starting with 'code-annotation-'. This function is primarily used to identify and remove annotation elements from code blocks before they are copied to the clipboard. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Initializing Tippy.js for Quarto Cross-References Source: https://github.com/pedropark99/zig-book/blob/main/docs/index.html This code iterates through cross-reference elements (`xrefs`) and initializes `tippyHover` (likely a wrapper for Tippy.js) for each. The hover callback dynamically fetches content for the tooltip. It determines if the xref is an internal hash link or an external URL, then fetches the corresponding HTML, parses it, extracts the relevant note or content, and sets it as the Tippy instance's content. It uses `processXRef` (an assumed external function) to prepare the content for display. ```JavaScript for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }, function(instance) { }); } ``` -------------------------------- ### Checking for Code Annotations - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/index.html Defines a utility function `isCodeAnnotation` that checks if a given DOM element has any class starting with 'code-annotation-'. This is used to identify and potentially remove annotation elements when copying code snippets. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Configuring Zig Build System for Image Filter Project Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/13-image-filter.html This `build.zig` script defines the build process for a Zig executable named `image_filter`. It specifies the main source file as `src/image_filter.zig` and configures standard target and optimization options. Crucially, it links the executable against the C Standard Library (`libc`) and the `libspng` system library, which is necessary for the application to compile and run correctly. ```Zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "image_filter", .root_source_file = b.path("src/image_filter.zig"), .target = target, .optimize = optimize, }); exe.linkLibC(); // Link to libspng library: exe.linkSystemLibrary("spng"); b.installArtifact(exe); } ``` -------------------------------- ### Checking for Code Annotation Class (JavaScript) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/15-vectors.html This utility function checks if a given DOM element has a class that starts with 'code-annotation-'. It iterates through the element's class list and returns `true` if a matching class is found, otherwise `false`. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Checking for Code Annotation Class in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/13-image-filter.html This utility function checks if a given DOM element has a class that starts with 'code-annotation-'. It's used to identify and handle specific types of code annotations within code blocks. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Executing a Compiled Zig Binary - Shell Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This command executes a binary executable named `hello_world` that has been compiled and placed in the `zig-out/bin` directory by the Zig build system. The `zig-out` directory serves as the default output location for compiled artifacts. The expected output of this command is 'Hello, world!'. ```Shell ./zig-out/bin/hello_world ``` -------------------------------- ### Check for Code Annotation Class in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html This helper function iterates through an element's class list to determine if it contains any class that starts with 'code-annotation-'. This is used to identify and potentially remove specific annotations from code blocks before copying their content. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Compiling a Zig Project with Native Build System - Shell Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This command initiates the Zig native build system. It automatically locates and executes the `build.zig` script in the current directory, which orchestrates the compilation and linking of the entire project. This approach streamlines the build process for complex projects, eliminating the need for manual compilation flags and module listings. ```Shell zig build ``` -------------------------------- ### Dereferencing a Pointer and Using its Value in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/05-pointers.html This example demonstrates dereferencing a pointer in Zig. It initializes a `number` and a `pointer` to its address. The `pointer.*` syntax is used to access the value pointed to by `pointer` (which is 5), allowing it to be doubled and then printed to standard debug output. ```Zig const number: u8 = 5; const pointer = &number; const doubled = 2 * pointer.*; std.debug.print("{d}\n", .{doubled}); ``` -------------------------------- ### Detecting Code Annotations - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/14-zig-c-interop.html This utility function, `isCodeAnnotation`, checks if a given DOM element has a class that starts with 'code-annotation-'. This is used to identify and potentially exclude specific parts of code blocks, such as annotations, when copying code to the clipboard. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Checking for Code Annotation Class - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/09-data-structures.html Defines a utility function `isCodeAnnotation` that checks if an HTML element has any CSS class starting with 'code-annotation-'. This is used to identify and potentially remove annotation elements from code blocks before copying. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Main Server Loop with HTTP Request Reading in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This `main` function in Zig sets up a basic TCP server, listens for incoming connections, and accepts a client connection. It initializes a 1000-byte buffer to all zeros to prevent uninitialized memory issues, then calls `Request.read_request` to read the client's HTTP request into this buffer. Finally, it prints the content of the buffer to standard output, demonstrating the received HTTP request. ```Zig const std = @import("std"); const SocketConf = @import("config.zig"); const Request = @import("request.zig"); const stdout = std.io.getStdOut().writer(); pub fn main() !void { const socket = try SocketConf.Socket.init(); try stdout.print("Server Addr: {any}\n", .{socket._address}); var server = try socket._address.listen(.{}); const connection = try server.accept(); var buffer: [1000]u8 = undefined; for (0..buffer.len) |i| { buffer[i] = 0; } _ = try Request.read_request( connection, buffer[0..buffer.len] ); try stdout.print("{s}\n", .{buffer}); } ``` -------------------------------- ### Replacing Substrings with std.mem.replace in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This example demonstrates `std.mem.replace()` for substituting occurrences of a substring within a string. It takes the element type (`u8`), the source string, the substring to find, the replacement substring, and a buffer for the result. The function returns the number of replacements made. ```Zig const str1 = "Hello"; var buffer: [5]u8 = undefined; const nrep = std.mem.replace( u8, str1, "el", "34", buffer[0..] ); try stdout.print("New string: {s}\n", .{buffer}); try stdout.print("N of replacements: {d}\n", .{nrep}); ``` -------------------------------- ### Compiling and Running Zig Module with zig run Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html The `zig run` command compiles and immediately executes the specified Zig module in a single step. This is convenient for quick testing and development, combining the `build-exe` and execution steps. ```Shell zig run src/main.zig ``` ```Shell Hello, world! ``` -------------------------------- ### BibTeX Entry for 'Introduction to Zig' Book Source: https://github.com/pedropark99/zig-book/blob/main/docs/index.html This BibTeX entry provides comprehensive citation details for the 'Introduction to Zig' book, including author, title, subtitle, publication month, edition, year, address, and URL. It is intended for academic or technical referencing to properly cite the work. ```BibTeX @book{pedro2024, author = {Pedro Duarte Faria}, title = {Introduction to Zig}, subtitle = {a project-based book}, month = {October}, edition = {1}, year = {2024}, address = {Belo Horizonte}, url = {https://github.com/pedropark99/zig-book} } ``` -------------------------------- ### Connecting to a Local Server using Python Requests Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/04-http-server.html This Python script uses the `requests` library to send a GET request to a local server running on `http://127.0.0.1:3490`. It demonstrates a programmatic way to initiate a connection and send an HTTP request to the server. ```Python import requests requests.get("http://127.0.0.1:3490") ``` -------------------------------- ### Checking for Code Annotation Class (JavaScript) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/10-stack-project.html This helper function iterates through the class list of a given HTML element to determine if it has any class that starts with 'code-annotation-'. This is used to identify and exclude code annotation elements when copying code snippets. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Declaring a Custom Build Step (Zig) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This snippet shows how to declare a new custom step in a Zig build script using `b.step()`. It names the step "run" and provides a brief description, making it available as a command-line option (e.g., `zig build run`) for users. ```Zig const run_step = b.step( "run", "Run the project" ); ``` -------------------------------- ### Executing a Custom Build Step in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This command-line instruction demonstrates how to trigger a specific build step, named 'run', that has been defined within the `build.zig` script. Executing this command will cause the Zig compiler to build the associated executable and then run it. ```Shell zig build run ``` -------------------------------- ### Iterating and Printing String Bytes in Hex in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This example shows how to iterate over the individual bytes of a string in Zig. It uses a `for` loop to access each `u8` byte and prints its hexadecimal representation using the `{X}` format specifier, useful for inspecting the underlying byte sequence. ```Zig const std = @import("std"); const stdout = std.io.getStdOut().writer(); pub fn main() !void { const string_object = "This is an example"; try stdout.print("Bytes that represents the string object: ", .{}); for (string_object) |byte| { try stdout.print("{X} ", .{byte}); } try stdout.print("\n", .{}); } ``` -------------------------------- ### Retrieving Color Scheme Sentinel (JavaScript) Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/10-stack-project.html This function retrieves the color scheme sentinel value. It first attempts to get the value from `localStorage` if the page is not a file URL. If not found or if it's a file URL, it falls back to the `localAlternateSentinel` variable. ```JavaScript const getColorSchemeSentinel = () => { if (!isFileUrl()) { const storageValue = window.localStorage.getItem("quarto-color-scheme"); return storageValue != null ? storageValue : localAlternateSentinel; } else { return localAlternateSentinel; } } ``` -------------------------------- ### Complete Singly Linked List Example in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/09-data-structures.html This comprehensive snippet combines all previous steps to demonstrate a full singly linked list implementation. It includes node definition, list initialization, node instantiation, and various insertion operations (`prepend`, `insertAfter`). Finally, it prints the total number of nodes using `list.len()`, showcasing basic list functionality. ```Zig const NodeU32 = struct { data: u32, node: std.SinglyLinkedList.Node = .{}, }; var list: std.SinglyLinkedList = .{}; var one: NodeU32 = .{ .data = 1 }; var two: NodeU32 = .{ .data = 2 }; var three: NodeU32 = .{ .data = 3 }; var five: NodeU32 = .{ .data = 5 }; list.prepend(&two.node); // {2} two.node.insertAfter(&five.node); // {2, 5} two.node.insertAfter(&three.node); // {2, 3, 5} list.prepend(&one.node); // {1, 2, 3, 5} try stdout.print("Number of nodes: {}", .{list.len()}); ``` -------------------------------- ### Checking for Code Annotation Class - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-base64.html This utility function checks if an HTML element has any CSS class that starts with 'code-annotation-'. It's used internally by the code copy functionality to identify and remove annotation elements before copying code. ```JavaScript const isCodeAnnotation = (el) => { for (const clz of el.classList) { if (clz.startsWith('code-annotation-')) { return true; } } return false; } ``` -------------------------------- ### Initializing C Structs with C Constructor Functions in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/14-zig-c-interop.html This snippet illustrates the common practice of initializing C structs in Zig by utilizing a constructor function provided by the C library (e.g., `hb_buffer_create()` from Harfbuzz). This approach simplifies initialization by delegating field assignment to the C function. ```Zig const c = @cImport({ @cInclude("hb.h"); }); var buf: c.hb_buffer_t = c.hb_buffer_create(); // Do stuff with the "buffer object" ``` -------------------------------- ### Initializing Google Analytics and Math Typesetting in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-base64.html This JavaScript snippet initializes Google Analytics for tracking page views and defines a function `typesetMath` to render mathematical expressions. It checks for either MathJax or KaTeX libraries and uses the available one to process elements with the 'math' class, ensuring proper display of equations on the webpage. ```JavaScript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-6CHJXK4CEV', { 'anonymize_ip': true}); const typesetMath = (el) => { if (window.MathJax) { // MathJax Typeset window.MathJax.typeset([el]); } else if (window.katex) { // KaTeX Render var mathElements = el.getElementsByClassName("math"); var macros = []; for (var i = 0; i < mathElements.length; i++) { var texText = mathElements[i].firstChild; if (mathElements[i].tagName == "SPAN") { window.katex.render(texText.data, mathElements[i], { displayMode: mathElements[i].classList.contains('display'), throwOnError: false, macros: macros, fleqn: false }); } } } } ``` -------------------------------- ### Initial Page Scroll and Transition Management in JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html This snippet ensures the page scrolls to the top (0,0) coordinates and initiates a transition management function for the 'body' element shortly after the page loads. This provides a smooth initial display and ensures the user starts at the top of the content. ```JavaScript setTimeout(() => { window.scrollTo(0, 0); manageTransitions("body", true); }, 40); ``` -------------------------------- ### Defining a C Struct for Interoperability Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/14-zig-c-interop.html This C header file defines a `User` struct with two members: `id` (an unsigned 64-bit integer) and `name` (a C-style string). This struct serves as an example for demonstrating how to create and interact with C objects from Zig code. ```C #include typedef struct { uint64_t id; char* name; } User; ``` -------------------------------- ### Configuring Tippy.js for Hover Tooltips - JavaScript Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html Defines a helper function `tippyHover` to configure and initialize Tippy.js tooltips. It sets common options like `allowHTML`, `maxWidth`, `delay`, `appendTo` (to parent element), `interactive`, `theme`, and `placement`. It also allows custom `contentFn`, `onTriggerFn`, and `onUntriggerFn` to be passed for dynamic content and event handling. ```JavaScript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Defining a Basic Function and Importing Modules in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-zig-weird.html This snippet demonstrates fundamental Zig syntax, including importing the standard library (`std`) and defining constants (`testing`). It also shows how to declare an `export`ed function `add` with explicitly typed arguments (`a: i32`, `b: i32`) and a return type (`i32`), illustrating Zig's strong typing and API exposure mechanism. ```Zig const std = @import("std"); const testing = std.testing; export fn add(a: i32, b: i32) i32 { return a + b; } ``` -------------------------------- ### Performing Pointer Arithmetic with Many-Item Pointer in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/05-pointers.html This example illustrates pointer arithmetic in Zig, similar to C. A many-item pointer ('[*]const i32') is initialized to point to the first element of an array. The pointer is then advanced using '+=' to access subsequent elements, demonstrating traversal through the array. ```Zig const ar = [_]i32{ 1, 2, 3, 4 }; var ptr: [*]const i32 = &ar; try stdout.print("{d}\n", .{ptr[0]}); ptr += 1; try stdout.print("{d}\n", .{ptr[0]}); ptr += 1; try stdout.print("{d}\n", .{ptr[0]}); ``` -------------------------------- ### Iterating Over Array Elements with For Loop in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/03-structs.html Demonstrates how to use a `for` loop to iterate over the elements of a fixed-size array (`[_]u8`). Each character's decimal representation is printed to standard output. This example shows direct value iteration. ```Zig const name = [_]u8{'P','e','d','r','o'}; for (name) |char| { try stdout.print("{d} | ", .{char}); } ``` -------------------------------- ### Initializing Google Analytics Data Layer Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/02-debugging.html This JavaScript snippet initializes the Google Analytics data layer and configures the gtag function to send page view data, including IP anonymization, for analytics tracking. It is a standard setup for integrating Google Analytics into a web page. ```JavaScript window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-6CHJXK4CEV', { 'anonymize_ip': true}); ``` -------------------------------- ### Creating User-Provided Build Options in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/07-build-system.html This Zig code snippet illustrates how to define a user-provided boolean option, `use_zlib`, using `b.option()` in a `build.zig` script. It shows how to conditionally link a system library (zlib) based on the value of this option, allowing for customizable build configurations. ```Zig const std = @import("std"); pub fn build(b: *std.Build) void { const use_zlib = b.option( bool, "use_zlib", "Should link to zlib?" ) orelse false; const exe = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("example.zig"), .target = b.host, }); if (use_zlib) { exe.linkSystemLibrary("zlib"); } b.installArtifact(exe); } ``` -------------------------------- ### Calculating Base64 Output Byte 0 (3-byte window) in Zig Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/01-base64.html This snippet calculates the first 6-bit output component (output[0]) when a full 3-byte input window is available. It shifts the first input byte (input[0]) two positions to the right, effectively taking its most significant 6 bits. This is the initial step in the 6-bit transformation. ```Zig input[0] >> 2 ``` -------------------------------- ### Illustrating Single Active Field in Zig Unions Source: https://github.com/pedropark99/zig-book/blob/main/docs/Chapters/09-error-handling.html This example demonstrates that only one field of a Zig union can be active at a time. After initializing `target` with `.azure`, attempting to access or assign to `.google` results in a runtime panic, highlighting the exclusive nature of union fields. ```Zig var target = LakeTarget { .azure = AzureBlob.init() }; // Only the `azure` data member exist inside // the `target` object, and, as a result, this // line below is invalid: target.google = GoogleGCP.init(); ```