github.com/tetratelabs/wazero@v1.7.3-0.20240513003603-48f702e154b5/internal/testing/binaryencoding/value.go (about) 1 package binaryencoding 2 3 import ( 4 "github.com/tetratelabs/wazero/internal/leb128" 5 "github.com/tetratelabs/wazero/internal/wasm" 6 ) 7 8 var noValType = []byte{0} 9 10 // encodedValTypes is a cache of size prefixed binary encoding of known val types. 11 var encodedValTypes = map[wasm.ValueType][]byte{ 12 wasm.ValueTypeI32: {1, wasm.ValueTypeI32}, 13 wasm.ValueTypeI64: {1, wasm.ValueTypeI64}, 14 wasm.ValueTypeF32: {1, wasm.ValueTypeF32}, 15 wasm.ValueTypeF64: {1, wasm.ValueTypeF64}, 16 wasm.ValueTypeExternref: {1, wasm.ValueTypeExternref}, 17 wasm.ValueTypeFuncref: {1, wasm.ValueTypeFuncref}, 18 wasm.ValueTypeV128: {1, wasm.ValueTypeV128}, 19 } 20 21 // EncodeValTypes fast paths binary encoding of common value type lengths 22 func EncodeValTypes(vt []wasm.ValueType) []byte { 23 // Special case nullary and parameter lengths of wasi_snapshot_preview1 to avoid excess allocations 24 switch uint32(len(vt)) { 25 case 0: // nullary 26 return noValType 27 case 1: // ex $wasi.fd_close or any result 28 if encoded, ok := encodedValTypes[vt[0]]; ok { 29 return encoded 30 } 31 case 2: // ex $wasi.environ_sizes_get 32 return []byte{2, vt[0], vt[1]} 33 case 4: // ex $wasi.fd_write 34 return []byte{4, vt[0], vt[1], vt[2], vt[3]} 35 case 9: // ex $wasi.fd_write 36 return []byte{9, vt[0], vt[1], vt[2], vt[3], vt[4], vt[5], vt[6], vt[7], vt[8]} 37 } 38 // Slow path others until someone complains with a valid signature 39 count := leb128.EncodeUint32(uint32(len(vt))) 40 return append(count, vt...) 41 }