github.com/primecitizens/pcz/std@v0.2.1/encoding/binfmt/wasm/parser.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  
     4  package wasm
     5  
     6  import (
     7  	"unsafe"
     8  
     9  	"github.com/primecitizens/pcz/std/encoding/binary"
    10  )
    11  
    12  const (
    13  	// Magic is the wasm file magic number.
    14  	Magic = 0x6d736100 // \0asm
    15  )
    16  
    17  type SectionID byte
    18  
    19  const (
    20  	Section_CUSTOM SectionID = iota
    21  	Section_TYPE
    22  	Section_IMPORT
    23  	Section_FUNCTION
    24  	Section_TABLE
    25  	Section_MEMORY
    26  	Section_GLOBAL
    27  	Section_EXPORT
    28  	Section_START
    29  	Section_ELEMENT
    30  	Section_CODE
    31  	Section_DATA
    32  	Section_DATA_COUNT
    33  )
    34  
    35  type Header struct {
    36  	Magic   binary.U32le[uint32]
    37  	Version binary.U32le[uint32]
    38  }
    39  
    40  func (h *Header) Decode(data []byte) (next []byte, ok bool) {
    41  	if len(data) < 8 {
    42  		return
    43  	}
    44  
    45  	h.Magic = *(*binary.U32le[uint32])(unsafe.Pointer(&data[0]))
    46  	h.Version = *(*binary.U32le[uint32])(unsafe.Pointer(&data[4]))
    47  	return data[8:], true
    48  }
    49  
    50  type Section struct {
    51  	ID   SectionID
    52  	Data []byte
    53  }
    54  
    55  func (sect *Section) Decode(data []byte) (next []byte, ok bool) {
    56  	if len(data) <= 4 {
    57  		return
    58  	}
    59  
    60  	sect.ID, data, ok = readU8[SectionID](data)
    61  	if !ok {
    62  		return
    63  	}
    64  
    65  	sz, data, ok := readU32(data)
    66  	if ok = ok && int(sz) <= len(data); !ok {
    67  		return
    68  	}
    69  
    70  	sect.Data = data[:sz]
    71  	return data[sz:], true
    72  }