-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
75 lines (57 loc) · 1.39 KB
/
utils.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
71
72
73
74
75
package main
// #include "gdp_types.h"
// #include "gdp_helper.h"
import "C"
import (
"bytes"
"encoding/gob"
"reflect"
"unsafe"
"github.com/tonyyanga/gdp-replicate/gdp"
"github.com/tonyyanga/gdp-replicate/policy"
)
func peerAddrToHash(addr C.PeerAddr) gdp.Hash {
var ret gdp.Hash
copy(ret[:], C.GoBytes(unsafe.Pointer(&addr.addr), 32))
return ret
}
func toCMsg(msg interface{}) C.Msg {
dest := &bytes.Buffer{}
encoder := gob.NewEncoder(dest)
gob.Register(&policy.GraphMsgContent{})
err := encoder.Encode(msg)
if err != nil {
panic(err)
}
// convert dest to a c array
length := dest.Len()
destBytes := dest.Bytes()
destCArray := C.malloc(C.size_t(C.int(length)))
// create a temporary slice as copy destination
slice := &reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(destCArray)),
Len: length,
Cap: length,
}
copy(*(*[]byte)(unsafe.Pointer(slice)), destBytes)
return C.Msg{
length: C.uint(length),
data: destCArray,
}
}
func toGoMsg(msg C.Msg) interface{} {
// convert a c array to a buffer
length := msg.length
srcCArray := msg.data
srcBytes := make([]byte, int(length))
copy(srcBytes, C.GoBytes(unsafe.Pointer(srcCArray), C.int(length)))
src := bytes.NewReader(srcBytes)
decoder := gob.NewDecoder(src)
gob.Register(&policy.GraphMsgContent{})
resp := &policy.GraphMsgContent{}
err := decoder.Decode(&resp)
if err != nil {
panic(err)
}
return resp
}