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