github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/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      });
    43      _greet(name) catch |err| @panic(switch (err) {
    44          error.OutOfMemory => "out of memory",
    45      });
    46  }
    47  
    48  // greeting is a WebAssembly export that accepts a string pointer (linear memory
    49  // offset) and returns a pointer/size pair packed into a uint64.
    50  //
    51  // Note: This uses a uint64 instead of two result values for compatibility with
    52  // WebAssembly 1.0.
    53  pub export fn greeting(message: [*]const u8, size: u32) u64 {
    54      const g = _greeting(message[0..size]) catch return 0;
    55      return stringToPtr(g);
    56  }
    57  
    58  // stringToPtr returns a pointer and size pair for the given string in a way
    59  // compatible with WebAssembly numeric types.
    60  pub fn stringToPtr(s: []const u8) u64 {
    61      const p: u64 = @ptrToInt(s.ptr);
    62      return p << 32 | s.len;
    63  }