-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
107 lines (101 loc) · 1.69 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
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
package DHTNet
import (
"bytes"
"encoding/binary"
"io"
"sync"
)
//整形转换成字节
func IntToBytes(n int) []byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
_ = binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
//字节转换成整形
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var x int32
_ =binary.Read(bytesBuffer, binary.BigEndian, &x)
return int(x)
}
func FullCopy(a,b io.ReadWriter) chan struct{}{
stop := make(chan struct{})
o := &sync.Once{}
go func() {
io.Copy(a, b)
o.Do(func() {
close(stop)
})
}()
go func() {
io.Copy(b, a)
o.Do(func() {
close(stop)
})
}()
return stop
}
func NetworkToBytes(network string) []byte {
switch network {
case "tcp":
return []byte{0}
case "tcp4":
return []byte{1}
case "tcp6":
return []byte{2}
case "udp":
return []byte{3}
case "udp4":
return []byte{4}
case "udp6":
return []byte{5}
default:
return []byte{255}
}
}
func BytesToNetwork(network []byte ) string {
switch network[0] {
case byte(0):
return "tcp"
case byte(1):
return "tcp4"
case byte(2):
return "tcp6"
case byte(3):
return "udp"
case byte(4):
return "udp4"
case byte(5):
return "udp6"
default:
return "tcp"
}
}
func PeerIdToDomain(peerId string) string {
res := ""
for _, c := range peerId{
if c > 'Z' || c < 'A'{
res += string(c)
}else {
res += "-"
res += string(c+32)
}
}
return res
}
func DomainToPeerId(domain string) string {
res := ""
needToTuen := false
for _, c := range domain{
if c == '-'{
needToTuen = true
}else if needToTuen {
res += string(c-32)
needToTuen = false
}else {
res += string(c)
}
}
return res
}