zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 866651a5a3397e5d10ee90f007f6ff6fa82c702d (tree)
parent 1bc92b1fde6e812de4a45ab3b2131d16151114d7
Author: Andrew Kelley <andrew@ziglang.org>
Date:   Fri, 12 Jun 2020 13:40:30 -0400

Merge pull request #5589 from kubkon/preopens-example

Add doc example for extracting WASI preopens
Diffstat:
Mdoc/langref.html.in | 27++++++++++++++++++++++++---
Mlib/std/fs/wasi.zig | 22++++++++++++++++++++++
2 files changed, 46 insertions(+), 3 deletions(-)

diff --git a/doc/langref.html.in b/doc/langref.html.in @@ -9702,7 +9702,7 @@ The result is 3</code></pre> {#header_open|WASI#} <p>Zig's support for WebAssembly System Interface (WASI) is under active development. Example of using the standard library and reading command line arguments:</p> - {#code_begin|exe|wasi#} + {#code_begin|exe|args#} {#target_wasi#} const std = @import("std"); @@ -9716,10 +9716,31 @@ pub fn main() !void { } } {#code_end#} - <pre><code>$ wasmer run wasi.wasm 123 hello -0: wasi.wasm + <pre><code>$ wasmtime args.wasm 123 hello +0: args.wasm 1: 123 2: hello</code></pre> + <p>A more interesting example would be extracting the list of preopens from the runtime. + This is now supported in the standard library via {#syntax#}std.fs.wasi.PreopenList{#endsyntax#}:</p> + {#code_begin|exe|preopens#} + {#target_wasi#} +const std = @import("std"); +const PreopenList = std.fs.wasi.PreopenList; + +pub fn main() !void { + var preopens = PreopenList.init(std.heap.page_allocator); + defer preopens.deinit(); + + try preopens.populate(); + + for (preopens.asSlice()) |preopen, i| { + std.debug.warn("{}: {}\n", .{ i, preopen }); + } +} + {#code_end#} + <pre><code>$ wasmtime --dir=. preopens.wasm +0: { .fd = 3, .Dir = '.' } +</code></pre> {#header_close#} {#header_close#} {#header_open|Targets#} diff --git a/lib/std/fs/wasi.zig b/lib/std/fs/wasi.zig @@ -35,6 +35,14 @@ pub const Preopen = struct { .@"type" = .{ .Dir = path }, }; } + + pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { + try out_stream.print("{{ .fd = {}, ", .{self.fd}); + switch (self.@"type") { + PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{path}), + } + return out_stream.print(" }}", .{}); + } }; /// Dynamically-sized array list of WASI preopens. This struct is a @@ -138,3 +146,17 @@ pub const PreopenList = struct { return self.buffer.toOwnedSlice(); } }; + +test "extracting WASI preopens" { + if (@import("builtin").os.tag != .wasi) return error.SkipZigTest; + + var preopens = PreopenList.init(std.testing.allocator); + defer preopens.deinit(); + + try preopens.populate(); + + std.testing.expectEqual(@as(usize, 1), preopens.asSlice().len); + const preopen = preopens.find(".") orelse unreachable; + std.testing.expect(std.mem.eql(u8, ".", preopen.@"type".Dir)); + std.testing.expectEqual(@as(usize, 3), preopen.fd); +}