github.com/lemon-mint/libuseful@v1.3.1-0.20220724073654-ee73785d5aa0/dumpstruct.go (about)

     1  package libuseful
     2  
     3  import (
     4  	"reflect"
     5  	"unsafe"
     6  )
     7  
     8  // DumpStruct takes a structure instance v as input and copies the memory to dst.
     9  //
    10  // If the size of dst is smaller than the size of v, a new byte slice is allocated.
    11  func DumpStruct[T any](dst []byte, v *T) []byte {
    12  	size := int(unsafe.Sizeof(*v))
    13  	if len(dst) >= int(size) {
    14  		dst = dst[:size]
    15  	} else {
    16  		dst = make([]byte, size)
    17  	}
    18  	BufH := (*reflect.SliceHeader)(unsafe.Pointer(&dst))
    19  
    20  	MemMove(unsafe.Pointer(BufH.Data), unsafe.Pointer(v), uintptr(size))
    21  	return dst
    22  }