github.com/taubyte/vm-wasm-utils@v1.0.2/binary/global.go (about) 1 package binary 2 3 import ( 4 "bytes" 5 "fmt" 6 7 wasm "github.com/taubyte/vm-wasm-utils" 8 ) 9 10 // decodeGlobal returns the api.Global decoded with the WebAssembly 1.0 (20191205) Binary Format. 11 // 12 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-global 13 func decodeGlobal(r *bytes.Reader, enabledFeatures wasm.Features) (*wasm.Global, error) { 14 gt, err := decodeGlobalType(r) 15 if err != nil { 16 return nil, err 17 } 18 19 init, err := decodeConstantExpression(r, enabledFeatures) 20 if err != nil { 21 return nil, err 22 } 23 24 return &wasm.Global{Type: gt, Init: init}, nil 25 } 26 27 // decodeGlobalType returns the wasm.GlobalType decoded with the WebAssembly 1.0 (20191205) Binary Format. 28 // 29 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-globaltype 30 func decodeGlobalType(r *bytes.Reader) (*wasm.GlobalType, error) { 31 vt, err := decodeValueTypes(r, 1) 32 if err != nil { 33 return nil, fmt.Errorf("read value type: %w", err) 34 } 35 36 ret := &wasm.GlobalType{ 37 ValType: vt[0], 38 } 39 40 b, err := r.ReadByte() 41 if err != nil { 42 return nil, fmt.Errorf("read mutablity: %w", err) 43 } 44 45 switch mut := b; mut { 46 case 0x00: // not mutable 47 case 0x01: // mutable 48 ret.Mutable = true 49 default: 50 return nil, fmt.Errorf("%w for mutability: %#x != 0x00 or 0x01", ErrInvalidByte, mut) 51 } 52 return ret, nil 53 } 54 55 // encodeGlobal returns the wasm.Global encoded in WebAssembly 1.0 (20191205) Binary Format. 56 // 57 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#global-section%E2%91%A0 58 func encodeGlobal(g *wasm.Global) (data []byte) { 59 var mutable byte 60 if g.Type.Mutable { 61 mutable = 1 62 } 63 data = []byte{g.Type.ValType, mutable} 64 data = append(data, encodeConstantExpression(g.Init)...) 65 return 66 }