This repository has been archived by the owner on Feb 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
92 lines (76 loc) · 1.77 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
package dctk
import (
"fmt"
"io"
"math/rand"
"net"
"strconv"
"strings"
"time"
"github.com/aler9/dctk/pkg/tiger"
)
var dirTTH = tiger.HashMust("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
func dcReadableQuery(request string) string {
if strings.HasPrefix(request, "tthl TTH/") {
return "tthl/" + strings.TrimPrefix(request, "tthl TTH/")
}
if strings.HasPrefix(request, "file TTH/") {
return "tth/" + strings.TrimPrefix(request, "file TTH/")
}
if request == "file files.xml.bz2" {
return "filelist"
}
return "\"" + request + "\""
}
func randomInt(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
func numtoa(num interface{}) string {
return fmt.Sprintf("%d", num)
}
func atoui(s string) uint {
ret, _ := strconv.ParseUint(s, 10, 64)
return uint(ret)
}
type connEstablisher struct {
Wait chan struct{}
Conn net.Conn
Error error
}
func newConnEstablisher(address string, timeout time.Duration, retries uint) *connEstablisher {
ce := &connEstablisher{
Wait: make(chan struct{}),
}
go func() {
ce.Conn, ce.Error = connWithTimeoutAndRetries(address, timeout, retries)
close(ce.Wait)
}()
return ce
}
func connWithTimeoutAndRetries(address string, timeout time.Duration, retries uint) (net.Conn, error) {
var err error
for i := uint(0); i < retries; i++ {
var conn net.Conn
conn, err = net.DialTimeout("tcp4", address, timeout)
if err == nil {
return conn, nil
}
}
return nil, err
}
type bytesWriteCloser struct {
buf []byte
offset int
}
func newBytesWriteCloser(buf []byte) io.WriteCloser {
return &bytesWriteCloser{buf: buf}
}
func (rc *bytesWriteCloser) Write(in []byte) (int, error) {
n := copy(rc.buf[rc.offset:], in)
rc.offset += n
return n, nil
}
func (rc *bytesWriteCloser) Close() error {
return nil
}