build: add oneshot parsing example

This commit is contained in:
torque 2023-09-24 14:45:01 -07:00
parent 54e4a14e38
commit 8684fab23c
Signed by: torque
SSH Key Fingerprint: SHA256:nCrXefBNo6EbjNSQhv0nXmEg/VuNq3sMF5b8zETw3Tk
2 changed files with 67 additions and 0 deletions

View File

@ -1,7 +1,45 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const nice = b.addModule("nice", .{
.source_file = .{ .path = "src/config.zig" },
});
add_examples(b, .{
.target = target,
.nice_mod = nice,
});
}
const ExampleOptions = struct {
target: std.zig.CrossTarget,
nice_mod: *std.Build.Module,
};
const Example = struct {
name: []const u8,
file: []const u8,
};
const examples = [_]Example{
.{ .name = "parse", .file = "examples/parse.zig" },
};
pub fn add_examples(b: *std.build, options: ExampleOptions) void {
const example_step = b.step("examples", "build examples");
inline for (examples) |example| {
const ex_exe = b.addExecutable(.{
.name = example.name,
.root_source_file = .{ .path = example.file },
.target = options.target,
.optimize = .Debug,
});
ex_exe.addModule("nice", options.nice_mod);
const install = b.addInstallArtifact(ex_exe, .{});
example_step.dependOn(&install.step);
}
}

29
examples/parse.zig Normal file
View File

@ -0,0 +1,29 @@
const std = @import("std");
const nice = @import("nice");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len < 2) return;
const data = try std.fs.cwd().readFileAlloc(allocator, args[1], 4_294_967_295);
var needfree = true;
defer if (needfree) allocator.free(data);
var parser = nice.Parser{ .allocator = allocator };
const document = try parser.parseBuffer(data);
defer document.deinit();
// free data memory to ensure that the parsed document is not holding
// references to it.
allocator.free(data);
needfree = false;
document.printDebug();
}