byteslice.go raw

   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).Elem()
  15  	sz := int(v.Type().Size())
  16  	var res []byte
  17  	h := (*reflect.SliceHeader)(unsafe.Pointer(&res))
  18  	h.Data = uintptr(unsafe.Pointer(v.UnsafeAddr()))
  19  	h.Cap = sz
  20  	h.Len = sz
  21  	return res
  22  }
  23  
  24  // Uint32 returns a byte slice view of a uint32 slice.
  25  func Uint32(s []uint32) []byte {
  26  	n := len(s)
  27  	if n == 0 {
  28  		return nil
  29  	}
  30  	blen := n * int(unsafe.Sizeof(s[0]))
  31  	return (*[1 << 30]byte)(unsafe.Pointer(&s[0]))[:blen:blen]
  32  }
  33  
  34  // Slice returns a byte slice view of a slice.
  35  func Slice(s interface{}) []byte {
  36  	v := reflect.ValueOf(s)
  37  	first := v.Index(0)
  38  	sz := int(first.Type().Size())
  39  	var res []byte
  40  	h := (*reflect.SliceHeader)(unsafe.Pointer(&res))
  41  	h.Data = first.UnsafeAddr()
  42  	h.Cap = v.Cap() * sz
  43  	h.Len = v.Len() * sz
  44  	return res
  45  }
  46