Skip to content

Instantly share code, notes, and snippets.

@shritesh
Last active April 15, 2019 21:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shritesh/315f002a4481c33131b7be8942d94b2e to your computer and use it in GitHub Desktop.
Save shritesh/315f002a4481c33131b7be8942d94b2e to your computer and use it in GitHub Desktop.
Fastly Zig Wasm
const std = @import("std");
const fmt = std.fmt;
extern fn hostcall_kvstore_upsert(
key_ptr: [*]const u8,
key_len: usize,
value_ptr: [*]const u8,
value_len: usize,
) bool;
extern fn hostcall_kvstore_get(
value_ptr_p: *[*]u8,
value_len_p: *usize,
key_ptr: [*]const u8,
key_len: usize,
) bool;
extern fn hostcall_kvstore_insert(
key_ptr: [*]const u8,
key_len: usize,
value_ptr: [*]const u8,
value_len: usize,
) bool;
extern fn hostcall_resp_set_body(
resp: i32,
body_ptr: [*]const u8,
body_len: usize,
) i32;
export fn run() void {
const key = "count";
const init = "0";
_ = hostcall_kvstore_upsert(&key, key.len, &init, init.len);
var value_ptr: [*]u8 = undefined;
var value_len: usize = 0;
_ = hostcall_kvstore_get(&value_ptr, &value_len, &key, key.len);
const count = fmt.parseInt(u32, value_ptr[0..value_len], 10) catch unreachable;
var buffer: [64]u8 = undefined;
const newcount = fmt.bufPrint(buffer[0..], "{}", count + 1) catch unreachable;
_ = hostcall_kvstore_insert(&key, key.len, newcount.ptr, newcount.len);
const body = fmt.bufPrint(buffer[0..], "Hello Webassembly from zig: {}", count + 1) catch unreachable;
_ = hostcall_resp_set_body(0, body.ptr, body.len);
}
@shritesh
Copy link
Author

shritesh commented Apr 10, 2019

Compile with zig build-exe -target wasm32-freestanding hostcalls.zig --release-fast --name module.wasm.

  • Go to: https://wasm.fastlylabs.com
  • Create empty WAT project
  • Delete line 5-7 from build.ts and save
  • Right click on the sidebar and upload module.wasm
  • Click Build and deploy

Note: ziglang/zig#2248 is required for memcpy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment