Makes examples runnable and pares down list (#458)

This deduplicates examples, leaving only the most maintained or targeted
ones. Notably, this makes each runnable, avoiding test dependencies.

Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
Crypt Keeper
2022-04-13 16:03:50 +08:00
committed by GitHub
parent 4cd4d8a590
commit 958ce19c0b
36 changed files with 306 additions and 532 deletions

1
examples/basic/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
add

3
examples/basic/README.md Normal file
View File

@@ -0,0 +1,3 @@
## Basic example
This example shows how to use WebAssembly and Go-defined functions with wazero.

69
examples/basic/add.go Normal file
View File

@@ -0,0 +1,69 @@
package main
import (
_ "embed"
"fmt"
"log"
"os"
"strconv"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
// main implements a basic function in both Go and WebAssembly.
func main() {
// Create a new WebAssembly Runtime.
r := wazero.NewRuntime()
// Add a module to the runtime named "wasm/math" which exports one function "add", implemented in WebAssembly.
wasm, err := r.InstantiateModuleFromCode([]byte(`(module $wasm/math
(func $add (param i32 i32) (result i32)
local.get 0
local.get 1
i32.add
)
(export "add" (func $add))
)`))
if err != nil {
log.Fatal(err)
}
defer wasm.Close()
// Add a module to the runtime named "host/math" which exports one function "add", implemented in Go.
host, err := r.NewModuleBuilder("host/math").
ExportFunction("add", func(v1, v2 uint32) uint32 {
return v1 + v2
}).Instantiate()
if err != nil {
log.Fatal(err)
}
defer host.Close()
// Read two args to add.
x, y := readTwoArgs()
// Call the same function in both modules and print the results to the console.
for _, mod := range []api.Module{wasm, host} {
add := mod.ExportedFunction("add")
results, err := add.Call(nil, x, y)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %d + %d = %d\n", mod.Name(), x, y, results[0])
}
}
func readTwoArgs() (uint64, uint64) {
x, err := strconv.ParseUint(os.Args[1], 10, 64)
if err != nil {
log.Fatalf("invalid arg %v: %v", os.Args[1], err)
}
y, err := strconv.ParseUint(os.Args[2], 10, 64)
if err != nil {
log.Fatalf("invalid arg %v: %v", os.Args[2], err)
}
return x, y
}

View File

@@ -0,0 +1,23 @@
package main
import (
"os"
)
// ExampleMain ensures the following will work:
//
// go build add.go
// ./add 7 9
func ExampleMain() {
// Save the old os.Args and replace with our example input.
oldArgs := os.Args
os.Args = []string{"add", "7", "9"}
defer func() { os.Args = oldArgs }()
main()
// Output:
// wasm/math: 7 + 9 = 16
// host/math: 7 + 9 = 16
}