forked from lesismal/nbio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
94 lines (85 loc) · 2.11 KB
/
convert.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package nbhttp
import (
"crypto/tls"
"encoding/binary"
"fmt"
"net"
"unsafe"
ltls "github.com/lesismal/llib/std/crypto/tls"
"github.com/soar4/nbio"
)
const (
uintptrSize = int(unsafe.Sizeof(uintptr(0)))
connValueSize = uintptrSize + 1
)
const (
connTypNONE byte = 0
connTypNBIO byte = 1
connTypTCP byte = 2
connTypUNIX byte = 3
connTypTLS byte = 4
connTypLTLS byte = 5
)
type connValue [connValueSize]byte
func conn2Array(conn net.Conn) (connValue, error) {
var p uintptr
var b connValue
switch vt := conn.(type) {
case *nbio.Conn:
p = uintptr(unsafe.Pointer(vt))
b[uintptrSize] = connTypNBIO
case *net.TCPConn:
p = uintptr(unsafe.Pointer(vt))
b[uintptrSize] = connTypTCP
case *net.UnixConn:
p = uintptr(unsafe.Pointer(vt))
b[uintptrSize] = connTypUNIX
case *tls.Conn:
p = uintptr(unsafe.Pointer(vt))
b[uintptrSize] = connTypTLS
case *ltls.Conn:
p = uintptr(unsafe.Pointer(vt))
b[uintptrSize] = connTypLTLS
default:
return b, fmt.Errorf("invalid conn type: %v", vt)
}
switch uintptrSize {
case 4:
binary.LittleEndian.PutUint32(b[:uintptrSize], uint32(p))
case 8:
binary.LittleEndian.PutUint64(b[:uintptrSize], uint64(p))
default:
return b, fmt.Errorf("unsupported platform: invalid uintptr size %v", uintptrSize)
}
return b, nil
}
func array2Conn(b connValue) (net.Conn, error) {
var p uintptr
switch uintptrSize {
case 4:
p = uintptr(binary.LittleEndian.Uint32(b[:uintptrSize]))
case 8:
p = uintptr(binary.LittleEndian.Uint64(b[:uintptrSize]))
default:
return nil, fmt.Errorf("unsupported platform: invalid uintptr size %v", uintptrSize)
}
switch b[uintptrSize] {
case connTypNBIO:
conn := *((**nbio.Conn)(unsafe.Pointer(&p)))
return conn, nil
case connTypTCP:
conn := *((**net.TCPConn)(unsafe.Pointer(&p)))
return conn, nil
case connTypUNIX:
conn := *((**net.UnixConn)(unsafe.Pointer(&p)))
return conn, nil
case connTypTLS:
conn := *((**tls.Conn)(unsafe.Pointer(&p)))
return conn, nil
case connTypLTLS:
conn := *((**ltls.Conn)(unsafe.Pointer(&p)))
return conn, nil
default:
}
return nil, fmt.Errorf("invalid conn type: %v", b[uintptrSize])
}