### Fetch zig-yaml Dependency Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `zig fetch` to download and save the zig-yaml library as a dependency. Example uses release tag 0.1.1. ```sh zig fetch --save=yaml https://github.com/kubkon/zig-yaml/archive/refs/tags/0.1.1.tar.gz ``` -------------------------------- ### Run YAML Spec Test Suite Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Build and run the zig-yaml test suite, including the YAML specification tests, by executing 'zig build test -Denable-spec-tests'. This command verifies the parser against the official YAML specification. ```bash zig build test -Denable-spec-tests ``` -------------------------------- ### Initialize Yaml Parser Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Initialize the Yaml parser with a source string. Ensure to deinitialize the parser when done to free resources. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; const gpa = std.testing.allocator; const source = \names: [ John Doe, MacIntosh, Jane Austin ] \numbers: \ - 10 \ - -8 \ - 6 \nested: \ some: one \ wick: john doe \finally: [ 8.17, \ 19.78 , 17 , \ 21 ] ; var yaml: Yaml = .{ .source = source }; defer yaml.deinit(gpa); ``` -------------------------------- ### Import zig-yaml Module Source: https://context7.com/kubkon/zig-yaml/llms.txt Import the zig-yaml module into your source files after adding it as a dependency. ```zig const yaml = @import("yaml"); const Yaml = yaml.Yaml; ``` -------------------------------- ### Add zig-yaml to build.zig Source: https://context7.com/kubkon/zig-yaml/llms.txt Integrate zig-yaml into your project by adding it as a dependency in `build.zig` and importing its module. ```zig const yaml = b.dependency("yaml", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("yaml", yaml.module("yaml")); ``` -------------------------------- ### Add zig-yaml Dependency to build.zig Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Integrate the fetched zig-yaml library into your project's build configuration by adding it as a dependency and importing its module. Ensure this is added after 'b.installArtifact(exe)'. ```zig // add that code after "b.installArtifact(exe)" line const yaml = b.dependency("yaml", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("yaml", yaml.module("yaml")); ``` -------------------------------- ### Fetch zig-yaml Release Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Use 'zig fetch' to download a specific release of the zig-yaml library into your project. This command saves the release archive for later use. ```zig zig fetch --save https://github.com/kubkon/zig-yaml/archive/refs/tags/[RELEASE_VERSION].tar.gz ``` ```zig zig fetch --save=yaml https://github.com/kubkon/zig-yaml/archive/refs/tags/0.1.1.tar.gz ``` -------------------------------- ### Clone Repository with Submodules Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Clone the zig-yaml repository, ensuring that all submodules are also fetched using the '--recurse-submodules' flag. This is necessary for running the spec test suite. ```bash git clone --recurse-submodules ``` -------------------------------- ### Load YAML Safely with Error Rendering Source: https://context7.com/kubkon/zig-yaml/llms.txt Safely loads YAML content, rendering colored diagnostics to stderr for `error.ParseFailure` before propagating the error. Ensure to deinitialize the `Yaml` instance and handle other errors. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn loadSafe(gpa: std.mem.Allocator, source: []const u8) !Yaml { var doc: Yaml = .{ .source = source }; doc.load(gpa) catch |err| switch (err) { error.ParseFailure => { // Render coloured diagnostics to stderr with line/column info doc.parse_errors.renderToStdErr(.{ .ttyconf = std.io.tty.detectConfig(std.io.getStdErr()), }); doc.deinit(gpa); return err; }, else => { doc.deinit(gpa); return err; }, }; return doc; } ``` -------------------------------- ### Load Untyped YAML Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Use 'Yaml.load' to parse YAML into an untyped, raw representation. This is useful for inspecting the structure before or without defining specific types. ```zig try yaml.load(gpa, source); try std.testing.expectEqual(untyped.docs.items.len, 1); const map = untyped.docs.items[0].map; try std.testing.expect(map.contains("names")); try std.testing.expectEqual(map.get("names").?.list.len, 3); ``` -------------------------------- ### Yaml.parse with multiple documents Source: https://context7.com/kubkon/zig-yaml/llms.txt Demonstrates parsing a YAML string containing multiple documents, separated by '---', into a Zig slice or array of a specified type. ```APIDOC ## `Yaml.parse` with multiple documents — Multi-doc YAML into a slice or array When the source contains multiple `---`-separated documents, `parse` maps them to a Zig slice (`[]T`) or fixed array (`[N]T`). ```zig const source = \--- \name: Alice \score: 100 \--- \name: Bob \score: 85 \... ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const Player = struct { name: []const u8, score: u32 }; const players = try doc.parse(arena.allocator(), []Player); // players.len == 2 // players[0].name == "Alice", players[0].score == 100 // players[1].name == "Bob", players[1].score == 85 ``` ``` -------------------------------- ### stringify (free function) Source: https://context7.com/kubkon/zig-yaml/llms.txt Serializes any native Zig value (struct, slice, array, scalar, union, enum, optional) directly to YAML text. Null optionals are omitted from the output. ```APIDOC ## `stringify` (free function) — Serialize any Zig value directly to YAML text The top-level `stringify` function in `lib.zig` skips the `Yaml` struct entirely and encodes a native Zig value (struct, slice, array, scalar, union, enum, optional) straight to a writer. Optionals that are `null` are omitted from the output. ```zig const std = @import("std"); const stringify = @import("yaml").stringify; const Point = struct { x: f64, y: f64, label: ?[]const u8 = null }; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var buf: std.Io.Writer.Allocating = .init(gpa); defer buf.deinit(); // Struct with a present optional try stringify(gpa, Point{ .x = 1.5, .y = -3.0, .label = "origin" }, &buf.writer); // => "x: 1.5\ny: -3\nlabel: origin" buf.reset(); // Struct with a null optional — field is omitted try stringify(gpa, Point{ .x = 0.0, .y = 0.0 }, &buf.writer); // => "x: 0\ny: 0" buf.reset(); // Slice of integers try stringify(gpa, @as([]const i32, &.{ 1, 2, 3 }), &buf.writer); // => "[ 1, 2, 3 ]" } ``` ``` -------------------------------- ### Parse YAML Source into Untyped Value Tree Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `Yaml.load` to parse YAML source string into a dynamic `Yaml.Value` tree. Handles syntax errors by returning `error.ParseFailure` and providing diagnostics via `Yaml.parse_errors`. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \names: [ Alice, Bob, Carol ] \scores: \ - 42 \ - 17 \ - 99 \active: true ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); doc.load(gpa) catch |err| switch (err) { error.ParseFailure => { doc.parse_errors.renderToStdErr(.{ .ttyconf = std.io.tty.detectConfig(std.io.getStdErr()) }); return err; }, else => return err, }; // docs.items[0] is the single implicit document const map = doc.docs.items[0].map; const names = map.get("names").?.list; std.debug.print("first name: {s}\n", .{names[0].scalar}); // Alice const scores = map.get("scores").?.list; std.debug.print("score count: {d}\n", .{scores.len}); // 3 const active = map.get("active").?.boolean; std.debug.print("active: {}\n", .{active}); // true } ``` -------------------------------- ### Traverse Untyped Yaml.Value Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `Yaml.Value` for reading YAML with an unknown schema. Helper accessors like `asScalar`, `asList`, and `asMap` provide safe pattern matching for dynamic data structures. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn walkValue(value: Yaml.Value, depth: usize) void { const indent = " " ** depth; // illustrative — use a runtime buffer in real code switch (value) { .empty => std.debug.print("{s}\n", .{indent}), .boolean => |b| std.debug.print("{s}{}\n", .{ indent, b }), .scalar => |s| std.debug.print("{s}{s}\n", .{ indent, s }), .list => |list| for (list) |elem| walkValue(elem, depth + 1), .map => |map| { var it = map.iterator(); while (it.next()) |entry| { std.debug.print("{s}{s}:\n", .{ indent, entry.key_ptr.* }); walkValue(entry.value_ptr.*, depth + 1); } }, } } // Usage var doc: Yaml = .{ .source = "key: [1, 2, 3]" }; defer doc.deinit(gpa); try doc.load(gpa); walkValue(doc.docs.items[0], 0); // key: // 1 // 2 // 3 ``` -------------------------------- ### Stringify Yaml Structure Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Convert a 'Yaml' structure back into its text representation using 'Yaml.stringify'. This function writes the output to a provided writer, such as standard output. ```zig try yaml.stringify(std.io.getStdOut().writer()); ``` -------------------------------- ### Handle YAML Parsing Errors Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Implement error handling for 'Yaml.load' to catch 'error.ParseFailure'. This allows for rendering detailed parsing errors to standard error using 'yaml.parse_errors.renderToStdErr'. ```zig var yaml: Yaml = .{ .source = source }; defer yaml.deinit(allocator); yaml.load(allocator) catch |err| switch (err) { error.ParseFailure => { assert(yaml.parse_errors.errorMessageCount() > 0); yaml.parse_errors.renderToStdErr(.{ .ttyconf = std.io.tty.detectConfig(std.io.getStdErr()) }); return error.ParseFailure; }, else => return err, }; ``` -------------------------------- ### Stringify Loaded Yaml Document to Writer Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `Yaml.stringify` to serialize a loaded `Yaml` document tree back to YAML text. This function writes to any `std.Io.Writer`, preserving document structure and markers. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \ \names: [ John Doe, MacIntosh, Jane Austin ] \numbers: \ - 10 \ - -8 \ - 6 \nested: \ some: one \ wick: john doe ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); // Write to stdout var buf: [4096]u8 = undefined; var writer = std.io.fixedBufferStream(&buf).writer(); try doc.stringify(&writer.any()); // Output: // --- // names: [ John Doe, MacIntosh, Jane Austin ] // numbers: [ 10, -8, 6 ] // nested: // some: one // wick: john doe // ... } ``` -------------------------------- ### Yaml.stringify Source: https://context7.com/kubkon/zig-yaml/llms.txt Serializes a loaded `Yaml` document back into YAML text format, writing to any `std.Io.Writer`. It preserves the structure of maps and lists and surrounds each document with '---' and '...' markers. ```APIDOC ## `Yaml.stringify` — Serialize a loaded `Yaml` document back to YAML text Writes the parsed `Yaml` document tree back to any `std.Io.Writer`, surrounding each document with `---` / `...` markers and preserving the structure of maps and lists. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \names: [ John Doe, MacIntosh, Jane Austin ] \numbers: \ - 10 \ - -8 \ - 6 \nested: \ some: one \ wick: john doe ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); // Write to stdout var buf: [4096]u8 = undefined; var writer = std.io.fixedBufferStream(&buf).writer(); try doc.stringify(&writer.any()); // Output: // --- // names: [ John Doe, MacIntosh, Jane Austin ] // numbers: [ 10, -8, 6 ] // nested: // some: one // wick: john doe // ... } ``` ``` -------------------------------- ### Parse Multi-Document YAML to Zig Slice Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `Yaml.parse` to map multiple `---`-separated YAML documents into a Zig slice (`[]T`) or fixed array (`[N]T`). Ensure the target type matches the YAML structure. ```zig const source = \ \--- \name: Alice \score: 100 \--- \name: Bob \score: 85 \... ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const Player = struct { name: []const u8, score: u32 }; const players = try doc.parse(arena.allocator(), []Player); // players.len == 2 // players[0].name == "Alice", players[0].score == 100 // players[1].name == "Bob", players[1].score == 85 ``` -------------------------------- ### Typed YAML Parsing with Domain Error Handling Source: https://context7.com/kubkon/zig-yaml/llms.txt Parses a `Yaml` document into a specific Zig struct, handling domain-specific errors like missing fields or type mismatches. Debug prints are used to indicate the type of parsing error encountered. ```zig // Typed parse — handle domain errors pub fn parseConfig(doc: Yaml, arena: std.mem.Allocator) !struct { port: u16 } { return doc.parse(arena, struct { port: u16 }) catch |err| switch (err) { error.StructFieldMissing => { std.debug.print("Config is missing required field 'port'\n", .{}); return err; }, error.TypeMismatch => { std.debug.print("Field type does not match YAML value\n", .{}); return err; }, else => return err, }; } ``` -------------------------------- ### Parse Typed YAML Source: https://github.com/kubkon/zig-yaml/blob/main/README.md Use 'Yaml.parse' to deserialize YAML into a specific Zig struct. This requires defining the expected structure beforehand and uses an arena allocator for memory management. ```zig const Simple = struct { names: []const []const u8, numbers: []const i16, nested: struct { some: []const u8, wick: []const u8, }, finally: [4]f16, }; var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const simple = try yaml.parse(arena.allocator(), Simple); try std.testing.expectEqual(simple.names.len, 3); ``` -------------------------------- ### Directly Stringify Zig Value to YAML Source: https://context7.com/kubkon/zig-yaml/llms.txt Use the top-level `stringify` function to encode native Zig values (structs, slices, arrays, scalars, unions, enums, optionals) directly to a writer, bypassing the `Yaml` struct. Null optionals are omitted. ```zig const std = @import("std"); const stringify = @import("yaml").stringify; const Point = struct { x: f64, y: f64, label: ?[]const u8 = null }; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); var buf: std.Io.Writer.Allocating = .init(gpa); defer buf.deinit(); // Struct with a present optional try stringify(gpa, Point{ .x = 1.5, .y = -3.0, .label = "origin" }, &buf.writer); // => "x: 1.5\ny: -3\nlabel: origin" buf.reset(); // Struct with a null optional — field is omitted try stringify(gpa, Point{ .x = 0.0, .y = 0.0 }, &buf.writer); // => "x: 0\ny: 0" buf.reset(); // Slice of integers try stringify(gpa, @as([]const i32, &.{ 1, 2, 3 }), &buf.writer); // => "[ 1, 2, 3 ]" } ``` -------------------------------- ### Yaml.load Source: https://context7.com/kubkon/zig-yaml/llms.txt Parses YAML source string into an untyped value tree. The `Yaml.Value` union can hold scalars, lists, maps, booleans, or empty values. Errors are reported via `error.ParseFailure` and detailed diagnostics are available in `Yaml.parse_errors`. ```APIDOC ## Yaml.load ### Description Parses the YAML source string stored in `Yaml.source` and populates `Yaml.docs` with one `Yaml.Value` per YAML document. The `Value` union can hold `.scalar`, `.list`, `.map`, `.boolean`, or `.empty`. On a syntax error the function returns `error.ParseFailure` and detailed diagnostics are available in `Yaml.parse_errors`. ### Method `Yaml.load(gpa: Allocator) anyerror!void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \ names: [ Alice, Bob, Carol ] scores: - 42 - 17 - 99 active: true ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); doc.load(gpa) catch |err| switch (err) { error.ParseFailure => { doc.parse_errors.renderToStdErr(.{ .ttyconf = std.io.tty.detectConfig(std.io.getStdErr()) }); return err; }, else => return err, }; // docs.items[0] is the single implicit document const map = doc.docs.items[0].map; const names = map.get("names").?.list; std.debug.print("first name: {s}\\n", .{names[0].scalar}); // Alice const scores = map.get("scores").?.list; std.debug.print("score count: {d}\\n", .{scores.len}); // 3 const active = map.get("active").?.boolean; std.debug.print("active: {}\\n", .{active}); // true } ``` ### Response #### Success Response (void) Populates `Yaml.docs` with parsed YAML documents. #### Response Example None ``` -------------------------------- ### Deserialize Loaded YAML into Typed Zig Value Source: https://context7.com/kubkon/zig-yaml/llms.txt Use `Yaml.parse` to convert a loaded `Yaml.Value` tree into a compile-time specified Zig type `T`. Supports various Zig types and handles missing optional fields by falling back to Zig defaults. Requires an arena allocator that outlives the returned value. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; const Config = struct { host: []const u8, port: u16, tls: bool = false, tags: ?[]const []const u8 = null, log_level: enum { debug, info, warn, err } = .info, }; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \host: localhost \port: 8080 \tls: true \tags: \ - web \ - api \log_level: debug ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const cfg = try doc.parse(arena.allocator(), Config); std.debug.print("host={s} port={d} tls={} tags={d} level={s}\n", .{ cfg.host, // "localhost" cfg.port, // 8080 cfg.tls, // true cfg.tags.?.len, // 2 @tagName(cfg.log_level), // "debug" }); } ``` -------------------------------- ### Yaml.Value Source: https://context7.com/kubkon/zig-yaml/llms.txt Represents an untyped, dynamic YAML value, returned by `Yaml.load`. It's a tagged union useful for reading YAML with unknown schemas. Helper accessors like `asScalar`, `asList`, and `asMap` provide safe pattern matching. ```APIDOC ## `Yaml.Value` — The untyped dynamic value type `Yaml.Value` is the tagged union returned by `Yaml.load`. It is useful for reading YAML whose schema is not known at compile time. Helper accessors `asScalar`, `asList`, and `asMap` return optionals for safe pattern matching. ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; pub fn walkValue(value: Yaml.Value, depth: usize) void { const indent = " " ** depth; // illustrative — use a runtime buffer in real code switch (value) { .empty => std.debug.print("{s}\n", .{indent}), .boolean => |b| std.debug.print("{s}{} ", .{ indent, b }), .scalar => |s| std.debug.print("{s}{s}\n", .{ indent, s }), .list => |list| for (list) |elem| walkValue(elem, depth + 1), .map => |map| { var it = map.iterator(); while (it.next()) |entry| { std.debug.print("{s}{s}:\n", .{ indent, entry.key_ptr.* }); walkValue(entry.value_ptr.*, depth + 1); } }, } } // Usage var doc: Yaml = .{ .source = "key: [1, 2, 3]" }; defer doc.deinit(gpa); try doc.load(gpa); walkValue(doc.docs.items[0], 0); // key: // 1 // 2 // 3 ``` ``` -------------------------------- ### Yaml.parse Source: https://context7.com/kubkon/zig-yaml/llms.txt Deserializes a loaded `Yaml.Value` tree into a compile-time specified Zig type `T`. Supports various Zig types including structs, slices, arrays, unions, enums, and numeric primitives. The provided allocator must outlive the returned value. ```APIDOC ## Yaml.parse ### Description Converts the already-loaded `Yaml.Value` tree into a concrete Zig type `T` supplied at compile time. Supported types: structs, slices (`[]T`), fixed arrays (`[N]T`), tagged unions, enums, booleans, integers (all bases: decimal, `0x`, `0o`), floats, optional fields, and single-pointer indirection (`*T`). Struct fields with Zig `_` are also matched against YAML keys that use `-`. Missing optional fields fall back to the field's Zig default value. The allocator passed must be an arena that outlives use of the returned value. ### Method `Yaml.parse(allocator: Allocator, comptime T: type) anyerror!T` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```zig const std = @import("std"); const Yaml = @import("yaml").Yaml; const Config = struct { host: []const u8, port: u16, tls: bool = false, tags: ?[]const []const u8 = null, log_level: enum { debug, info, warn, err } = .info, }; pub fn main() !void { var gpa_state = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_state.deinit(); const gpa = gpa_state.allocator(); const source = \ host: localhost port: 8080 tls: true tags: - web - api log_level: debug ; var doc: Yaml = .{ .source = source }; defer doc.deinit(gpa); try doc.load(gpa); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const cfg = try doc.parse(arena.allocator(), Config); std.debug.print("host={s} port={d} tls={} tags={d} level={s}\\n", .{ cfg.host, // "localhost" cfg.port, // 8080 cfg.tls, // true cfg.tags.?.len, // 2 @tagName(cfg.log_level), // "debug" }); } ``` ### Response #### Success Response (T) Deserialized Zig value of type `T`. #### Response Example None ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.