github.com/taubyte/vm-wasm-utils@v1.0.2/binary/export.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 decodeExport(r *bytes.Reader) (i *wasm.Export, err error) {
    12  	i = &wasm.Export{}
    13  
    14  	if i.Name, _, err = decodeUTF8(r, "export name"); err != nil {
    15  		return nil, err
    16  	}
    17  
    18  	b, err := r.ReadByte()
    19  	if err != nil {
    20  		return nil, fmt.Errorf("error decoding export kind: %w", err)
    21  	}
    22  
    23  	i.Type = b
    24  	switch i.Type {
    25  	case wasm.ExternTypeFunc, wasm.ExternTypeTable, wasm.ExternTypeMemory, wasm.ExternTypeGlobal:
    26  		if i.Index, _, err = leb128.DecodeUint32(r); err != nil {
    27  			return nil, fmt.Errorf("error decoding export index: %w", err)
    28  		}
    29  	default:
    30  		return nil, fmt.Errorf("%w: invalid byte for exportdesc: %#x", ErrInvalidByte, b)
    31  	}
    32  	return
    33  }
    34  
    35  // encodeExport returns the wasm.Export encoded in WebAssembly 1.0 (20191205) Binary Format.
    36  //
    37  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#export-section%E2%91%A0
    38  func encodeExport(i *wasm.Export) []byte {
    39  	data := encodeSizePrefixed([]byte(i.Name))
    40  	data = append(data, i.Type)
    41  	data = append(data, leb128.EncodeUint32(i.Index)...)
    42  	return data
    43  }