byteslice.go 895 B

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