wa-lang.org/wazero@v1.0.2/internal/wasm/binary/encoder.go (about)

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