github.com/taubyte/vm-wasm-utils@v1.0.2/counts.go (about) 1 package wasm 2 3 import "fmt" 4 5 // ImportFuncCount returns the possibly empty count of imported functions. This plus SectionElementCount of 6 // SectionIDFunction is the size of the function index namespace. 7 func (m *Module) ImportFuncCount() uint32 { 8 return m.importCount(ExternTypeFunc) 9 } 10 11 // ImportTableCount returns the possibly empty count of imported tables. This plus SectionElementCount of SectionIDTable 12 // is the size of the table index namespace. 13 func (m *Module) ImportTableCount() uint32 { 14 return m.importCount(ExternTypeTable) 15 } 16 17 // ImportMemoryCount returns the possibly empty count of imported memories. This plus SectionElementCount of 18 // SectionIDMemory is the size of the memory index namespace. 19 func (m *Module) ImportMemoryCount() uint32 { 20 return m.importCount(ExternTypeMemory) // TODO: once validation happens on decode, this is zero or one. 21 } 22 23 // ImportGlobalCount returns the possibly empty count of imported globals. This plus SectionElementCount of 24 // SectionIDGlobal is the size of the global index namespace. 25 func (m *Module) ImportGlobalCount() uint32 { 26 return m.importCount(ExternTypeGlobal) 27 } 28 29 // importCount returns the count of a specific type of import. This is important because it is easy to mistake the 30 // length of the import section with the count of a specific kind of import. 31 func (m *Module) importCount(et ExternType) (res uint32) { 32 for _, im := range m.ImportSection { 33 if im.Type == et { 34 res++ 35 } 36 } 37 return 38 } 39 40 // SectionElementCount returns the count of elements in a given section ID 41 // 42 // For example... 43 // * SectionIDType returns the count of FunctionType 44 // * SectionIDCustom returns one if the NameSection is present 45 // * SectionIDHostFunction returns the count of HostFunctionSection 46 // * SectionIDExport returns the count of unique export names 47 func (m *Module) SectionElementCount(sectionID SectionID) uint32 { // element as in vector elements! 48 switch sectionID { 49 case SectionIDCustom: 50 if m.NameSection != nil { 51 return 1 52 } 53 return 0 54 case SectionIDType: 55 return uint32(len(m.TypeSection)) 56 case SectionIDImport: 57 return uint32(len(m.ImportSection)) 58 case SectionIDFunction: 59 return uint32(len(m.FunctionSection)) 60 case SectionIDTable: 61 return uint32(len(m.TableSection)) 62 case SectionIDMemory: 63 if m.MemorySection != nil { 64 return 1 65 } 66 return 0 67 case SectionIDGlobal: 68 return uint32(len(m.GlobalSection)) 69 case SectionIDExport: 70 return uint32(len(m.ExportSection)) 71 case SectionIDStart: 72 if m.StartSection != nil { 73 return 1 74 } 75 return 0 76 case SectionIDElement: 77 return uint32(len(m.ElementSection)) 78 case SectionIDCode: 79 return uint32(len(m.CodeSection)) 80 case SectionIDData: 81 return uint32(len(m.DataSection)) 82 default: 83 panic(fmt.Errorf("BUG: unknown section: %d", sectionID)) 84 } 85 }