github.com/taubyte/vm-wasm-utils@v1.0.2/binary/import.go (about) 1 package binary 2 3 import ( 4 "bytes" 5 "fmt" 6 7 wasm "github.com/taubyte/vm-wasm-utils" 8 "github.com/taubyte/vm-wasm-utils/leb128" 9 ) 10 11 func decodeImport( 12 r *bytes.Reader, 13 idx uint32, 14 memorySizer func(minPages uint32, maxPages *uint32) (min, capacity, max uint32), 15 enabledFeatures wasm.Features, 16 ) (i *wasm.Import, err error) { 17 i = &wasm.Import{} 18 if i.Module, _, err = decodeUTF8(r, "import module"); err != nil { 19 return nil, fmt.Errorf("import[%d] error decoding module: %w", idx, err) 20 } 21 22 if i.Name, _, err = decodeUTF8(r, "import name"); err != nil { 23 return nil, fmt.Errorf("import[%d] error decoding name: %w", idx, err) 24 } 25 26 b, err := r.ReadByte() 27 if err != nil { 28 return nil, fmt.Errorf("import[%d] error decoding type: %w", idx, err) 29 } 30 i.Type = b 31 switch i.Type { 32 case wasm.ExternTypeFunc: 33 i.DescFunc, _, err = leb128.DecodeUint32(r) 34 case wasm.ExternTypeTable: 35 i.DescTable, err = decodeTable(r, enabledFeatures) 36 case wasm.ExternTypeMemory: 37 i.DescMem, err = decodeMemory(r, memorySizer) 38 case wasm.ExternTypeGlobal: 39 i.DescGlobal, err = decodeGlobalType(r) 40 default: 41 err = fmt.Errorf("%w: invalid byte for importdesc: %#x", ErrInvalidByte, b) 42 } 43 if err != nil { 44 return nil, fmt.Errorf("import[%d] %s[%s.%s]: %w", idx, wasm.ExternTypeName(i.Type), i.Module, i.Name, err) 45 } 46 return 47 } 48 49 // encodeImport returns the wasm.Import encoded in WebAssembly 1.0 (20191205) Binary Format. 50 // 51 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-import 52 func encodeImport(i *wasm.Import) []byte { 53 data := encodeSizePrefixed([]byte(i.Module)) 54 data = append(data, encodeSizePrefixed([]byte(i.Name))...) 55 data = append(data, i.Type) 56 switch i.Type { 57 case wasm.ExternTypeFunc: 58 data = append(data, leb128.EncodeUint32(i.DescFunc)...) 59 case wasm.ExternTypeTable: 60 data = append(data, wasm.RefTypeFuncref) 61 data = append(data, encodeLimitsType(i.DescTable.Min, i.DescTable.Max)...) 62 case wasm.ExternTypeMemory: 63 maxPtr := &i.DescMem.Max 64 if !i.DescMem.IsMaxEncoded { 65 maxPtr = nil 66 } 67 data = append(data, encodeLimitsType(i.DescMem.Min, maxPtr)...) 68 case wasm.ExternTypeGlobal: 69 g := i.DescGlobal 70 var mutable byte 71 if g.Mutable { 72 mutable = 1 73 } 74 data = append(data, g.ValType, mutable) 75 default: 76 panic(fmt.Errorf("invalid externtype: %s", wasm.ExternTypeName(i.Type))) 77 } 78 return data 79 }