github.com/wasilibs/wazerox@v0.0.0-20240124024944-4923be63ab5f/internal/wasm/binary/limits.go (about)

     1  package binary
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/wasilibs/wazerox/internal/leb128"
     8  )
     9  
    10  // decodeLimitsType returns the `limitsType` (min, max) decoded with the WebAssembly 1.0 (20191205) Binary Format.
    11  //
    12  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#limits%E2%91%A6
    13  //
    14  // Extended in threads proposal: https://webassembly.github.io/threads/core/binary/types.html#limits
    15  func decodeLimitsType(r *bytes.Reader) (min uint32, max *uint32, shared bool, err error) {
    16  	var flag byte
    17  	if flag, err = r.ReadByte(); err != nil {
    18  		err = fmt.Errorf("read leading byte: %v", err)
    19  		return
    20  	}
    21  
    22  	switch flag {
    23  	case 0x00, 0x02:
    24  		min, _, err = leb128.DecodeUint32(r)
    25  		if err != nil {
    26  			err = fmt.Errorf("read min of limit: %v", err)
    27  		}
    28  	case 0x01, 0x03:
    29  		min, _, err = leb128.DecodeUint32(r)
    30  		if err != nil {
    31  			err = fmt.Errorf("read min of limit: %v", err)
    32  			return
    33  		}
    34  		var m uint32
    35  		if m, _, err = leb128.DecodeUint32(r); err != nil {
    36  			err = fmt.Errorf("read max of limit: %v", err)
    37  		} else {
    38  			max = &m
    39  		}
    40  	default:
    41  		err = fmt.Errorf("%v for limits: %#x not in (0x00, 0x01, 0x02, 0x03)", ErrInvalidByte, flag)
    42  	}
    43  
    44  	shared = flag == 0x02 || flag == 0x03
    45  
    46  	return
    47  }