github.com/jxskiss/gopkg@v0.17.3/reflectx/runtime.go (about)

     1  package reflectx
     2  
     3  import (
     4  	"github.com/jxskiss/gopkg/internal/linkname"
     5  	"reflect"
     6  	"unsafe"
     7  )
     8  
     9  func add(p unsafe.Pointer, offset uintptr) unsafe.Pointer {
    10  	return unsafe.Pointer(uintptr(p) + offset)
    11  }
    12  
    13  // ArrayAt returns the i-th element of p,
    14  // an array whose elements are elemSize bytes wide.
    15  // The array pointed at by p must have at least i+1 elements:
    16  // it is invalid (but impossible to check here) to pass i >= len,
    17  // because then the result will point outside the array.
    18  func ArrayAt(p unsafe.Pointer, i int, elemSize uintptr) unsafe.Pointer {
    19  	return add(p, uintptr(i)*elemSize)
    20  }
    21  
    22  // MakeSlice makes a new slice of the given reflect.Type and length, capacity.
    23  func MakeSlice(elemTyp reflect.Type, length, capacity int) (slice interface{}, header *SliceHeader) {
    24  	elemRType := ToRType(elemTyp)
    25  	data := linkname.Reflect_unsafe_NewArray(unsafe.Pointer(elemRType), capacity)
    26  	header = &SliceHeader{
    27  		Data: data,
    28  		Len:  length,
    29  		Cap:  capacity,
    30  	}
    31  	slice = *(*interface{})(unsafe.Pointer(&EmptyInterface{
    32  		RType: SliceOf(elemRType),
    33  		Word:  unsafe.Pointer(header),
    34  	}))
    35  	return
    36  }
    37  
    38  // MapLen returns the length of the given map interface{} value.
    39  // The provided m must be a map, else it panics.
    40  func MapLen(m interface{}) int {
    41  	return linkname.Reflect_maplen(EfaceOf(&m).Word)
    42  }
    43  
    44  // TypedMemMove exports the typedmemmove function in reflect package.
    45  func TypedMemMove(rtype *RType, dst, src unsafe.Pointer) {
    46  	linkname.Reflect_typedmemmove(unsafe.Pointer(rtype), dst, src)
    47  }
    48  
    49  // TypedSliceCopy exports the typedslicecopy function in reflect package.
    50  func TypedSliceCopy(elemRType *RType, dst, src SliceHeader) int {
    51  	return linkname.Reflect_typedslicecopy(unsafe.Pointer(elemRType), dst, src)
    52  }