~eliasnaur/gio

gio/internal/unsafe/unsafe.go -rw-r--r-- 873 bytes
ef7b3e75Jack Mordaunt widget: delete whole words with key modifier 2 days ago
                                                                                
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
46
// SPDX-License-Identifier: Unlicense OR MIT

package unsafe

import (
	"reflect"
	"unsafe"
)

// 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())
	return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(first.UnsafeAddr())))),
		Len:  v.Len() * sz,
		Cap:  v.Cap() * sz,
	}))
}

// SliceOf returns a slice from a (native) pointer.
func SliceOf(s uintptr) []byte {
	if s == 0 {
		return nil
	}
	sh := reflect.SliceHeader{
		Data: s,
		Len:  1 << 30,
		Cap:  1 << 30,
	}
	return *(*[]byte)(unsafe.Pointer(&sh))
}

// GoString convert a NUL-terminated C string
// to a Go string.
func GoString(s []byte) string {
	i := 0
	for {
		if s[i] == 0 {
			break
		}
		i++
	}
	return string(s[:i])
}