-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbinary.go
70 lines (59 loc) · 1.45 KB
/
binary.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package cgolmnl
import (
"C"
"reflect"
"syscall"
"unsafe"
)
// make copy
func (nlh *Nlmsg) MarshalBinary() ([]byte, error) {
dst := make([]byte, nlh.Len)
copy(dst, C.GoBytes(unsafe.Pointer(nlh.Nlmsghdr), C.int(nlh.Len)))
return dst, nil
}
// confide receiver len
func (nlh *Nlmsg) UnmarshalBinary(data []byte) error {
if len(data) < int(MNL_NLMSG_HDRLEN) {
return syscall.EINVAL // errors.New("too short data length")
}
if int(nlh.Len) < len(data) {
return syscall.EINVAL // errors.New("too short receiver size")
}
var dst []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&dst))
h.Cap = int(nlh.Len)
h.Len = int(nlh.Len)
h.Data = uintptr(unsafe.Pointer(nlh.Nlmsghdr))
copy(dst, data)
return nil
}
func (attr *Nlattr) MarshalBinary() ([]byte, error) {
dst := make([]byte, attr.Len)
copy(dst, C.GoBytes(unsafe.Pointer(attr), C.int(attr.Len)))
return dst, nil
}
// confide receiver len
func (attr *Nlattr) UnmarshalBinary(data []byte) error {
if len(data) < SizeofNlattr {
return syscall.EINVAL
}
if int(attr.Len) < len(data) {
return syscall.EINVAL
}
var dst []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&dst))
h.Cap = int(attr.Len)
h.Len = int(attr.Len)
h.Data = uintptr(unsafe.Pointer(attr))
copy(dst, data)
return nil
}
// C.GoBytes() returns copy
func SharedBytes(p unsafe.Pointer, plen int) []byte {
var b []byte
h := (*reflect.SliceHeader)(unsafe.Pointer(&b))
h.Cap = plen
h.Len = plen
h.Data = uintptr(p)
return b
}