github.com/taubyte/vm-wasm-utils@v1.0.2/binary/table.go (about)

     1  package binary
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	wasm "github.com/taubyte/vm-wasm-utils"
     8  )
     9  
    10  // decodeTable returns the wasm.Table decoded with the WebAssembly 1.0 (20191205) Binary Format.
    11  //
    12  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-table
    13  func decodeTable(r *bytes.Reader, enabledFeatures wasm.Features) (*wasm.Table, error) {
    14  	tableType, err := r.ReadByte()
    15  	if err != nil {
    16  		return nil, fmt.Errorf("read leading byte: %v", err)
    17  	}
    18  
    19  	if tableType != wasm.RefTypeFuncref {
    20  		if err := enabledFeatures.Require(wasm.FeatureReferenceTypes); err != nil {
    21  			return nil, fmt.Errorf("table type funcref is invalid: %w", err)
    22  		}
    23  	}
    24  
    25  	min, max, err := decodeLimitsType(r)
    26  	if err != nil {
    27  		return nil, fmt.Errorf("read limits: %v", err)
    28  	}
    29  	if min > wasm.MaximumFunctionIndex {
    30  		return nil, fmt.Errorf("table min must be at most %d", wasm.MaximumFunctionIndex)
    31  	}
    32  	if max != nil {
    33  		if *max < min {
    34  			return nil, fmt.Errorf("table size minimum must not be greater than maximum")
    35  		}
    36  	}
    37  	return &wasm.Table{Min: min, Max: max, Type: tableType}, nil
    38  }
    39  
    40  // encodeTable returns the wasm.Table encoded in WebAssembly 1.0 (20191205) Binary Format.
    41  //
    42  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-table
    43  func encodeTable(i *wasm.Table) []byte {
    44  	return append([]byte{i.Type}, encodeLimitsType(i.Min, i.Max)...)
    45  }