wa-lang.org/wazero@v1.0.2/examples/allocation/zig/testdata/greet.zig (about) 1 const std = @import("std"); 2 const allocator = std.heap.page_allocator; 3 4 extern "env" fn log(ptr: [*]const u8, size: u32) void; 5 6 // _log prints a message to the console using log. 7 pub fn _log(message: []const u8) void { 8 log(message.ptr, message.len); 9 } 10 11 pub export fn malloc(length: usize) ?[*]u8 { 12 const buff = allocator.alloc(u8, length) catch return null; 13 return buff.ptr; 14 } 15 16 pub export fn free(buf: [*]u8, length: usize) void { 17 allocator.free(buf[0..length]); 18 } 19 20 pub fn _greeting(name: []const u8) ![]u8 { 21 return try std.fmt.allocPrint( 22 allocator, 23 "Hello, {s}!", 24 .{name}, 25 ); 26 } 27 28 // _greet prints a greeting to the console. 29 pub fn _greet(name: []const u8) !void { 30 const s = try std.fmt.allocPrint( 31 allocator, 32 "wasm >> {s}", 33 .{name}, 34 ); 35 _log(s); 36 } 37 38 // greet is a WebAssembly export that accepts a string pointer (linear memory offset) and calls greet. 39 pub export fn greet(message: [*]const u8, size: u32) void { 40 const name = _greeting(message[0..size]) catch |err| @panic(switch (err) { 41 error.OutOfMemory => "out of memory", 42 else => "unexpected error", 43 }); 44 _greet(name) catch |err| @panic(switch (err) { 45 error.OutOfMemory => "out of memory", 46 else => "unexpected error", 47 }); 48 } 49 50 // greeting is a WebAssembly export that accepts a string pointer (linear memory 51 // offset) and returns a pointer/size pair packed into a uint64. 52 // 53 // Note: This uses a uint64 instead of two result values for compatibility with 54 // WebAssembly 1.0. 55 pub export fn greeting(message: [*]const u8, size: u32) u64 { 56 const g = _greeting(message[0..size]) catch return 0; 57 return stringToPtr(g); 58 } 59 60 // stringToPtr returns a pointer and size pair for the given string in a way 61 // compatible with WebAssembly numeric types. 62 pub fn stringToPtr(s: []const u8) u64 { 63 const p: u64 = @ptrToInt(s.ptr); 64 return p << 32 | s.len; 65 }