github.com/wfusion/gofusion@v1.1.14/async/utils.go (about)

     1  package async
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  func wrapParams(fn any) (argType reflect.Type, embed bool) {
     9  	typ := reflect.TypeOf(fn)
    10  
    11  	inLength := typ.NumIn()
    12  	if inLength == 1 {
    13  		return
    14  	}
    15  	if inLength == 2 {
    16  		return typ.In(1), false
    17  	}
    18  
    19  	fields := make([]reflect.StructField, 0, inLength)
    20  	for i := 1; i < inLength; i++ {
    21  		fields = append(fields, reflect.StructField{
    22  			Name:      fmt.Sprintf("Arg%X", i+1),
    23  			PkgPath:   "",
    24  			Type:      typ.In(i),
    25  			Tag:       "",
    26  			Offset:    0,
    27  			Index:     nil,
    28  			Anonymous: false,
    29  		})
    30  	}
    31  
    32  	return reflect.StructOf(fields), true
    33  }
    34  
    35  func unwrapParams(typ reflect.Type, embed bool, arg any) (params []any) {
    36  	if typ == nil {
    37  		return
    38  	}
    39  
    40  	if !embed {
    41  		return []any{arg}
    42  	}
    43  
    44  	argVal := reflect.Indirect(reflect.ValueOf(arg))
    45  	num := argVal.Type().NumField()
    46  	params = make([]any, 0, num)
    47  	for i := 0; i < num; i++ {
    48  		params = append(params, argVal.Field(i).Interface())
    49  	}
    50  
    51  	return
    52  }
    53  
    54  func setParams(typ reflect.Type, embed bool, params ...any) (arg any) {
    55  	if typ == nil {
    56  		return
    57  	}
    58  
    59  	argValPtr := reflect.New(typ)
    60  	argVal := argValPtr.Elem()
    61  	if !embed {
    62  		if len(params) > 0 {
    63  			argVal.Set(reflect.ValueOf(params[0]))
    64  		}
    65  		return argValPtr.Interface()
    66  	}
    67  
    68  	for i := 0; i < len(params); i++ {
    69  		ft := argVal.Field(i)
    70  		ft.Set(reflect.ValueOf(params[i]).Convert(ft.Type()))
    71  	}
    72  	return argValPtr.Interface()
    73  }