-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathutil.go
137 lines (113 loc) · 2.41 KB
/
util.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 nymo
import (
"bytes"
"crypto/aes"
"encoding/binary"
"io"
"net/http"
"sync"
"time"
"unsafe"
"google.golang.org/protobuf/proto"
)
func sameCohort(target, pov uint32) bool {
return pov == target || target == cohortNumber
}
func (u *User) peerSameCohort(peer uint32) bool {
return sameCohort(peer, u.cohort)
}
func sendMessage(conn io.Writer, m proto.Message) error {
data, err := proto.Marshal(m)
if err != nil {
return err
}
if len(data) > maxPacketSize {
panic("exceed size")
}
buf := make([]byte, uint16Size+len(data))
encoding.PutUint16(buf, uint16(len(data)))
copy(buf[uint16Size:], data)
_, err = conn.Write(buf)
return err
}
func recvMessage(conn io.Reader, m proto.Message) error {
var size uint16
err := binary.Read(conn, encoding, &size)
if err != nil {
return err
}
buf := make([]byte, size)
_, err = io.ReadFull(conn, buf)
if err != nil {
return err
}
return proto.Unmarshal(buf, m)
}
type writeFlusher struct {
w io.Writer
f http.Flusher
}
func (w *writeFlusher) Write(p []byte) (n int, err error) {
defer w.f.Flush()
return w.w.Write(p)
}
func padBlock(input []byte) []byte {
pad := (len(input)/aes.BlockSize+1)*aes.BlockSize - len(input)
return append(input, bytes.Repeat([]byte{byte(pad)}, pad)...)
}
func trimBlock(input []byte) []byte {
c := input[len(input)-1]
b := int(c)
if b <= 0 || b > aes.BlockSize {
return nil
}
for i := len(input) - b; i < len(input)-1; i++ {
if input[i] != c {
return nil
}
}
return input[:len(input)-b]
}
func truncateHash(hash []byte) [hashTruncate]byte {
if len(hash) < hashTruncate {
panic("out of bounds")
}
return *(*[hashTruncate]byte)(unsafe.Pointer(&hash[0]))
}
func copyHash(hash []byte) [hashSize]byte {
if len(hash) < hashSize {
panic("out of bounds")
}
return *(*[hashSize]byte)(unsafe.Pointer(&hash[0]))
}
type peerRetrier struct {
l sync.Mutex
m map[string]time.Time
}
func (p *peerRetrier) addSelf(url string) {
p.l.Lock()
defer p.l.Unlock()
p.m[url] = emptyTime
}
func (p *peerRetrier) add(url string, timeout time.Duration) {
ddl := time.Now().Add(timeout)
p.l.Lock()
defer p.l.Unlock()
t, ok := p.m[url]
if !ok || (t != emptyTime && t.Before(ddl)) {
p.m[url] = ddl
}
}
func (p *peerRetrier) noRetry(url string) bool {
p.l.Lock()
defer p.l.Unlock()
t, ok := p.m[url]
if !ok {
return false
}
if t == emptyTime || time.Until(t) > 0 {
return true
}
delete(p.m, url)
return false
}