-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
137 lines (110 loc) · 2.41 KB
/
codec.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package multiaddr
import (
"encoding/binary"
"fmt"
"net"
"strconv"
"strings"
)
func stringToBytes(s string) ([]byte, error) {
// consume trailing slashes
s = strings.TrimRight(s, "/")
b := []byte{}
sp := strings.Split(s, "/")
if sp[0] != "" {
return nil, fmt.Errorf("invalid multiaddr, must begin with /")
}
// consume first empty elem
sp = sp[1:]
for len(sp) > 0 {
p := ProtocolWithName(sp[0])
if p == nil {
return nil, fmt.Errorf("no protocol with name %s", sp[0])
}
b = append(b, CodeToVarint(p.Code)...)
sp = sp[1:]
if p.Size > 0 {
a := addressStringToBytes(p, sp[0])
b = append(b, a...)
sp = sp[1:]
}
}
return b, nil
}
func bytesToString(b []byte) (ret string, err error) {
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
ret = ""
err = e.(error)
}
}()
s := ""
for len(b) > 0 {
code, n := ReadVarintCode(b)
b = b[n:]
p := ProtocolWithCode(code)
if p == nil {
return "", fmt.Errorf("no protocol with code %d", code)
}
s = strings.Join([]string{s, "/", p.Name}, "")
if p.Size > 0 {
a := addressBytesToString(p, b[:(p.Size/8)])
if len(a) > 0 {
s = strings.Join([]string{s, "/", a}, "")
}
b = b[(p.Size / 8):]
}
}
return s, nil
}
func bytesSplit(b []byte) (ret [][]byte, err error) {
// panic handler, in case we try accessing bytes incorrectly.
defer func() {
if e := recover(); e != nil {
ret = [][]byte{}
err = e.(error)
}
}()
ret = [][]byte{}
for len(b) > 0 {
code, n := ReadVarintCode(b)
p := ProtocolWithCode(code)
if p == nil {
return [][]byte{}, fmt.Errorf("no protocol with code %d", b[0])
}
length := n + (p.Size / 8)
ret = append(ret, b[:length])
b = b[length:]
}
return ret, nil
}
func addressStringToBytes(p *Protocol, s string) []byte {
switch p.Code {
case P_IP4: // ipv4
return net.ParseIP(s).To4()
case P_IP6: // ipv6
return net.ParseIP(s).To16()
// tcp udp dccp sctp
case P_TCP, P_UDP, P_DCCP, P_SCTP:
b := make([]byte, 2)
i, err := strconv.Atoi(s)
if err == nil {
binary.BigEndian.PutUint16(b, uint16(i))
}
return b
}
return []byte{}
}
func addressBytesToString(p *Protocol, b []byte) string {
switch p.Code {
// ipv4,6
case P_IP4, P_IP6:
return net.IP(b).String()
// tcp udp dccp sctp
case P_TCP, P_UDP, P_DCCP, P_SCTP:
i := binary.BigEndian.Uint16(b)
return strconv.Itoa(int(i))
}
return ""
}