github.com/Seikaijyu/gio@v0.0.1/internal/byteslice/byteslice.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  // Package byteslice provides byte slice views of other Go values  such as
     4  // slices and structs.
     5  package byteslice
     6  
     7  import (
     8  	"reflect"
     9  	"unsafe"
    10  )
    11  
    12  // Struct returns a byte slice view of a struct.
    13  func Struct(s interface{}) []byte {
    14  	v := reflect.ValueOf(s)
    15  	sz := int(v.Elem().Type().Size())
    16  	return unsafe.Slice((*byte)(unsafe.Pointer(v.Pointer())), sz)
    17  }
    18  
    19  // Uint32 returns a byte slice view of a uint32 slice.
    20  func Uint32(s []uint32) []byte {
    21  	n := len(s)
    22  	if n == 0 {
    23  		return nil
    24  	}
    25  	blen := n * int(unsafe.Sizeof(s[0]))
    26  	return unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), blen)
    27  }
    28  
    29  // Slice returns a byte slice view of a slice.
    30  func Slice(s interface{}) []byte {
    31  	v := reflect.ValueOf(s)
    32  	first := v.Index(0)
    33  	sz := int(first.Type().Size())
    34  	res := unsafe.Slice((*byte)(unsafe.Pointer(v.Pointer())), sz*v.Cap())
    35  	return res[:sz*v.Len()]
    36  }