github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zreflect/value.go (about)

     1  package zreflect
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  func ValueOf(v interface{}) reflect.Value {
     9  	if v == nil {
    10  		return reflect.Value{}
    11  	}
    12  	valueLayout := (*Value)(unsafe.Pointer(&v))
    13  	value := Value{}
    14  	value.typ = valueLayout.typ
    15  	value.ptr = valueLayout.ptr
    16  	f := flag(toRType(value.typ).Kind())
    17  	if ifaceIndir(value.typ) {
    18  		f |= 1 << 7
    19  	}
    20  	value.flag = f
    21  	return value.Native()
    22  }
    23  
    24  func NewValue(v interface{}) Value {
    25  	switch vv := v.(type) {
    26  	case Value:
    27  		return vv
    28  	case reflect.Value:
    29  		return *(*Value)(unsafe.Pointer(&vv))
    30  	default:
    31  		value := Value{}
    32  		if v == nil {
    33  			return value
    34  		}
    35  		valueLayout := (*Value)(unsafe.Pointer(&v))
    36  		value.typ = valueLayout.typ
    37  		value.ptr = valueLayout.ptr
    38  		f := flag(toRType(value.typ).Kind())
    39  		if ifaceIndir(value.typ) {
    40  			f |= 1 << 7
    41  		}
    42  		value.flag = f
    43  		return value
    44  	}
    45  }
    46  
    47  func (v Value) Native() reflect.Value {
    48  	return *(*reflect.Value)(unsafe.Pointer(&v))
    49  }
    50  
    51  func (v Value) Type() Type {
    52  	return v.typ
    53  }