MCPcopy Create free account
hub / github.com/bytecodealliance/wasmtime-go / Example_gcd

Function Example_gcd

example_test.go:719–768  ·  view source on GitHub ↗

An example of a wasm module which calculates the GCD of two numbers

()

Source from the content-addressed store, hash-verified

717
718// An example of a wasm module which calculates the GCD of two numbers
719func Example_gcd() {
720 store := wasmtime.NewStore(wasmtime.NewEngine())
721 wasm, err := wasmtime.Wat2Wasm(`
722 (module
723 (func $gcd (param i32 i32) (result i32)
724 (local i32)
725 block ;; label = @1
726 block ;; label = @2
727 local.get 0
728 br_if 0 (;@2;)
729 local.get 1
730 local.set 2
731 br 1 (;@1;)
732 end
733 loop ;; label = @2
734 local.get 1
735 local.get 0
736 local.tee 2
737 i32.rem_u
738 local.set 0
739 local.get 2
740 local.set 1
741 local.get 0
742 br_if 0 (;@2;)
743 end
744 end
745 local.get 2
746 )
747 (export "gcd" (func $gcd))
748 )
749 `)
750 if err != nil {
751 log.Fatal(err)
752 }
753 module, err := wasmtime.NewModule(store.Engine, wasm)
754 if err != nil {
755 log.Fatal(err)
756 }
757 instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{})
758 if err != nil {
759 log.Fatal(err)
760 }
761 run := instance.GetFunc(store, "gcd")
762 result, err := run.Call(store, 6, 27)
763 if err != nil {
764 log.Fatal(err)
765 }
766 fmt.Printf("gcd(6, 27) = %d\n", result.(int32))
767 // Output: gcd(6, 27) = 3
768}
769
770type sessionData struct {
771 request_id int32

Callers

nothing calls this directly

Calls 2

GetFuncMethod · 0.95
CallMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…