all: replace unsafe slice operations with unsafe.Slice

Signed-off-by: Elias Naur <mail@eliasnaur.com>
This commit is contained in:
Elias Naur
2022-03-02 15:37:34 +01:00
parent af8ca96414
commit fea2f888bb
6 changed files with 13 additions and 38 deletions
+6 -15
View File
@@ -11,14 +11,9 @@ import (
// 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
v := reflect.ValueOf(s)
sz := int(v.Elem().Type().Size())
return unsafe.Slice((*byte)(unsafe.Pointer(v.Pointer())), sz)
}
// Uint32 returns a byte slice view of a uint32 slice.
@@ -28,7 +23,7 @@ func Uint32(s []uint32) []byte {
return nil
}
blen := n * int(unsafe.Sizeof(s[0]))
return (*[1 << 30]byte)(unsafe.Pointer(&s[0]))[:blen:blen]
return unsafe.Slice((*byte)(unsafe.Pointer(&s[0])), blen)
}
// Slice returns a byte slice view of a slice.
@@ -36,10 +31,6 @@ 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
res := unsafe.Slice((*byte)(unsafe.Pointer(v.Pointer())), sz*v.Cap())
return res[:sz*v.Len()]
}