mirror of
https://git.sr.ht/~eliasnaur/gio
synced 2026-07-06 18:05:35 +00:00
5894127204
The only users were GOOS=windows code, which can use golang.org/x/sys/windows.BytePtrToString instead. Signed-off-by: Elias Naur <mail@eliasnaur.com>
47 lines
968 B
Go
47 lines
968 B
Go
// SPDX-License-Identifier: Unlicense OR MIT
|
|
|
|
package unsafe
|
|
|
|
import (
|
|
"reflect"
|
|
"unsafe"
|
|
)
|
|
|
|
// StructView returns a byte slice view of a struct.
|
|
func StructView(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
|
|
}
|
|
|
|
// BytesView returns a byte slice view of a slice.
|
|
func BytesView(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
|
|
}
|
|
|
|
// SliceOf returns a slice from a (native) pointer.
|
|
func SliceOf(s uintptr) []byte {
|
|
if s == 0 {
|
|
return nil
|
|
}
|
|
var res []byte
|
|
h := (*reflect.SliceHeader)(unsafe.Pointer(&res))
|
|
h.Data = s
|
|
h.Cap = 1 << 30
|
|
h.Len = 1 << 30
|
|
return res
|
|
}
|