github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/internal/avatar/avatar.go (about)

     1  package avatar
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  type (
     9  	Avatar struct {
    10  		model interface{}
    11  		body  reflect.Value
    12  		//typ    reflect.Type
    13  		fields []interface{}
    14  	}
    15  	emptyInterface struct {
    16  		typ  *struct{}
    17  		word unsafe.Pointer
    18  	}
    19  )
    20  
    21  func New(target reflect.Value) *Avatar {
    22  	val := target.Elem()
    23  	////t := reflect.TypeOf(val)
    24  	return &Avatar{
    25  		//	model: target,
    26  		body: val,
    27  		//typ:  target,
    28  	}
    29  }
    30  
    31  func (self *Avatar) SetFields(fields ...interface{}) {
    32  	self.fields = append(self.fields, fields...)
    33  }
    34  
    35  func (self *Avatar) swap() func(in []reflect.Value) []reflect.Value {
    36  	return func(in []reflect.Value) []reflect.Value {
    37  		newV := reflect.New(self.body.Type()).Elem()
    38  		//p := newV.Interface()
    39  		//ptr0 := uintptr((*emptyInterface)(unsafe.Pointer(&p)).word)
    40  		//ptr1 := ptr0 + self.typ.Field(0).Offset
    41  		//*((*string)(unsafe.Pointer(ptr0))) = "fadf" //self.fields[0]
    42  		//var i interface{} = &midWare{name: "fdfd"}
    43  
    44  		//*((*interface{})(unsafe.Pointer(ptr1))) = &self.fields[1]
    45  		for i := 0; i < newV.NumField(); i++ {
    46  			newV.Field(i).Set(reflect.ValueOf(self.fields[i]))
    47  		}
    48  		return []reflect.Value{newV}
    49  	}
    50  }
    51  
    52  func (self *Avatar) NewCreator() func() interface{} {
    53  	var creator func() interface{}
    54  	fnVal := reflect.ValueOf(&creator).Elem()
    55  	// Make a function of the right type.
    56  	v := reflect.MakeFunc(fnVal.Type(), self.swap())
    57  	fnVal.Set(v)
    58  	return creator
    59  }