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

     1  package binary
     2  
     3  import wasm "github.com/taubyte/vm-wasm-utils"
     4  
     5  var sizePrefixedName = []byte{4, 'n', 'a', 'm', 'e'}
     6  
     7  // EncodeModule implements wasm.EncodeModule for the WebAssembly 1.0 (20191205) Binary Format.
     8  // Note: If saving to a file, the conventional extension is wasm
     9  // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-format%E2%91%A0
    10  func EncodeModule(m *wasm.Module) (bytes []byte) {
    11  	bytes = append(Magic, version...)
    12  	if m.SectionElementCount(wasm.SectionIDType) > 0 {
    13  		bytes = append(bytes, encodeTypeSection(m.TypeSection)...)
    14  	}
    15  	if m.SectionElementCount(wasm.SectionIDImport) > 0 {
    16  		bytes = append(bytes, encodeImportSection(m.ImportSection)...)
    17  	}
    18  	if m.SectionElementCount(wasm.SectionIDFunction) > 0 {
    19  		bytes = append(bytes, encodeFunctionSection(m.FunctionSection)...)
    20  	}
    21  	if m.SectionElementCount(wasm.SectionIDTable) > 0 {
    22  		bytes = append(bytes, encodeTableSection(m.TableSection)...)
    23  	}
    24  	if m.SectionElementCount(wasm.SectionIDMemory) > 0 {
    25  		bytes = append(bytes, encodeMemorySection(m.MemorySection)...)
    26  	}
    27  	if m.SectionElementCount(wasm.SectionIDGlobal) > 0 {
    28  		bytes = append(bytes, encodeGlobalSection(m.GlobalSection)...)
    29  	}
    30  	if m.SectionElementCount(wasm.SectionIDExport) > 0 {
    31  		bytes = append(bytes, encodeExportSection(m.ExportSection)...)
    32  	}
    33  	if m.SectionElementCount(wasm.SectionIDStart) > 0 {
    34  		bytes = append(bytes, encodeStartSection(*m.StartSection)...)
    35  	}
    36  	if m.SectionElementCount(wasm.SectionIDElement) > 0 {
    37  		bytes = append(bytes, encodeElementSection(m.ElementSection)...)
    38  	}
    39  	if m.SectionElementCount(wasm.SectionIDCode) > 0 {
    40  		bytes = append(bytes, encodeCodeSection(m.CodeSection)...)
    41  	}
    42  	if m.SectionElementCount(wasm.SectionIDData) > 0 {
    43  		bytes = append(bytes, encodeDataSection(m.DataSection)...)
    44  	}
    45  	if m.SectionElementCount(wasm.SectionIDCustom) > 0 {
    46  		// >> The name section should appear only once in a module, and only after the data section.
    47  		// See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-namesec
    48  		if m.NameSection != nil {
    49  			nameSection := append(sizePrefixedName, encodeNameSectionData(m.NameSection)...)
    50  			bytes = append(bytes, encodeSection(wasm.SectionIDCustom, nameSection)...)
    51  		}
    52  	}
    53  	return
    54  }