gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/unsafe/unsafe.go (about) 1 package unsafe 2 3 import ( 4 sliceUnsafe "gitee.com/sy_183/go-common/slice/unsafe" 5 "unsafe" 6 ) 7 8 func Convert[SRC, DST any](src SRC) DST { 9 return *(*DST)(unsafe.Pointer(&src)) 10 } 11 12 func ConvertPointer[SRC, DST any](src *SRC) *DST { 13 return (*DST)(unsafe.Pointer(src)) 14 } 15 16 func ConvertFromPointer[SRC, DST any](src *SRC) DST { 17 return *(*DST)(unsafe.Pointer(src)) 18 } 19 20 func ConvertToPointer[SRC, DST any](src SRC) *DST { 21 return (*DST)(unsafe.Pointer(&src)) 22 } 23 24 func FromPointer[X any](p unsafe.Pointer) X { 25 return *(*X)(p) 26 } 27 28 func ToPointer[X any](x X) unsafe.Pointer { 29 return *(*unsafe.Pointer)(unsafe.Pointer(&x)) 30 } 31 32 func Offset[X any, F any](x *X, offset uintptr) F { 33 return *(*F)(unsafe.Pointer(uintptr(unsafe.Pointer(x)) + offset)) 34 } 35 36 func OffsetPointer[X any, F any](x *X, offset uintptr) *F { 37 return (*F)(unsafe.Pointer(uintptr(unsafe.Pointer(x)) + offset)) 38 } 39 40 type bytes struct { 41 ptr unsafe.Pointer 42 len int 43 cap int 44 } 45 46 func Copy(dst, src unsafe.Pointer, size int) { 47 switch size { 48 case 0: 49 return 50 case 1: 51 *(*uint8)(dst) = *(*uint8)(src) 52 case 2: 53 *(*uint16)(dst) = *(*uint16)(src) 54 case 4: 55 *(*uint32)(dst) = *(*uint32)(src) 56 case 8: 57 *(*uint64)(dst) = *(*uint64)(src) 58 case 16: 59 *(*complex128)(dst) = *(*complex128)(src) 60 case 24: 61 *(*[24]byte)(dst) = *(*[24]byte)(src) 62 case 32: 63 *(*[32]byte)(dst) = *(*[32]byte)(src) 64 default: 65 copy( 66 sliceUnsafe.Build[byte](dst, size, size), 67 sliceUnsafe.Build[byte](src, size, size), 68 ) 69 } 70 } 71 72 func Unescape[O any](op *O) *O { 73 oup := uintptr(unsafe.Pointer(op)) 74 return (*O)(unsafe.Pointer(oup)) 75 }