-
Notifications
You must be signed in to change notification settings - Fork 0
/
byteslice.go
45 lines (40 loc) · 1.02 KB
/
byteslice.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// SPDX-License-Identifier: Unlicense OR MIT
// Package byteslice provides byte slice views of other Go values such as
// slices and structs.
package byteslice
import (
"reflect"
"unsafe"
)
// Struct returns a byte slice view of a struct.
func Struct(s interface{}) []byte {
v := reflect.ValueOf(s).Elem()
sz := int(v.Type().Size())
var res []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&res))
h.Data = uintptr(unsafe.Pointer(v.UnsafeAddr()))
h.Cap = sz
h.Len = sz
return res
}
// Uint32 returns a byte slice view of a uint32 slice.
func Uint32(s []uint32) []byte {
n := len(s)
if n == 0 {
return nil
}
blen := n * int(unsafe.Sizeof(s[0]))
return (*[1 << 30]byte)(unsafe.Pointer(&s[0]))[:blen:blen]
}
// Slice returns a byte slice view of a slice.
func Slice(s interface{}) []byte {
v := reflect.ValueOf(s)
first := v.Index(0)
sz := int(first.Type().Size())
var res []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&res))
h.Data = first.UnsafeAddr()
h.Cap = v.Cap() * sz
h.Len = v.Len() * sz
return res
}