github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/notsafe/notsafe.go (about) 1 // Package notsafe provides unsafe helper functions 2 package notsafe 3 4 import ( 5 "reflect" 6 "unsafe" 7 ) 8 9 // GetTypeSize retrieves size of a type T 10 func GetTypeSize[T any]() uintptr { 11 var t T 12 return unsafe.Sizeof(t) 13 } 14 15 // GetArrayPointer retrieves the pointer of a slice underlying array 16 func GetArrayPointer[T any](elements []T) unsafe.Pointer { 17 return unsafe.Pointer(GetSliceHeader(elements).Data) 18 } 19 20 // GetArrayElem returns an element by index from the array referenced by an unsafe pointer 21 func GetArrayElem[T any](array unsafe.Pointer, index int, elemSize uintptr) T { 22 return *(*T)(GetArrayElemRef(array, index, elemSize)) 23 } 24 25 // GetArrayElemRef returns an element's pointer by index from the array referenced by an unsafe pointer 26 func GetArrayElemRef(array unsafe.Pointer, index int, elemSize uintptr) unsafe.Pointer { 27 return unsafe.Pointer(uintptr(array) + uintptr(index)*elemSize) 28 } 29 30 // GetLen returns the length of elements 31 func GetLen[T any](elements []T) int { 32 return GetSliceHeader(elements).Len 33 } 34 35 // GetSliceHeader retrieves the SliceHeader of elements 36 func GetSliceHeader[T any](elements []T) *reflect.SliceHeader { 37 return GetSliceHeaderByRef(unsafe.Pointer(&elements)) 38 } 39 40 // GetSliceHeaderByRef retrieves the SliceHeader of elements by an unsafe pointer 41 func GetSliceHeaderByRef(elements unsafe.Pointer) *reflect.SliceHeader { 42 return (*reflect.SliceHeader)(elements) 43 } 44 45 // InHeap is generic link to runtime.inheap 46 func InHeap[T any](t *T) bool { 47 return inheap(uintptr(unsafe.Pointer(t))) 48 } 49 50 //go:linkname inheap runtime.inheap 51 func inheap(p uintptr) bool