github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/wasm/abi/register.go (about)

     1  package abi
     2  
     3  import (
     4  	"reflect"
     5  	"sync"
     6  
     7  	types "github.com/machinefi/w3bstream/pkg/modules/wasm/abi/types"
     8  )
     9  
    10  var (
    11  	abis = sync.Map{}
    12  )
    13  
    14  type Factory func(types.Instance) types.Context
    15  
    16  func RegisterABI(name string, factory interface{}) {
    17  	abis.Store(name, factory)
    18  }
    19  
    20  func GetABI(i types.Instance, name string) types.Context {
    21  	if i == nil || name == "" {
    22  		return nil
    23  	}
    24  	v, ok := abis.Load(name)
    25  	if !ok {
    26  		return nil
    27  	}
    28  
    29  	abiNames := i.GetModule().GetABINameList()
    30  	for _, abiName := range abiNames {
    31  		if name == abiName {
    32  			f := v.(Factory)
    33  			return f(i)
    34  		}
    35  	}
    36  	return nil
    37  }
    38  
    39  func GetABIList(i types.Instance) []types.Context {
    40  	if i == nil {
    41  		return nil
    42  	}
    43  
    44  	factories := map[uintptr]struct{}{}
    45  	res := make([]types.Context, 0)
    46  
    47  	abiNames := i.GetModule().GetABINameList()
    48  	for _, name := range abiNames {
    49  		v, ok := abis.Load(name)
    50  		if !ok {
    51  			continue
    52  		}
    53  		ptr := reflect.ValueOf(v).Pointer()
    54  		if _, ok := factories[ptr]; !ok {
    55  			res = append(res, v.(Factory)(i))
    56  			factories[ptr] = struct{}{}
    57  		}
    58  	}
    59  	return res
    60  }