-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
89 lines (81 loc) · 1.6 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
package Torrent
import (
"crypto/sha1"
"fmt"
bencode "github.com/JRonak/Bencode"
metadata "github.com/JRonak/Torrent/MetaData"
"math/rand"
"strconv"
)
const (
KB = 1024
MB = 1024 * 1024
MIN = 60
HOUR = 3600
)
func intToTime(time int) string {
if time >= HOUR {
return fmt.Sprintf("%2d Hour %2d Mins", time/HOUR, (time%HOUR)/MIN)
} else if time >= MIN {
return fmt.Sprintf("%2d Mins %2d Seconds", time/MIN, (time % MIN))
} else {
return fmt.Sprintf("%2d Seconds", time)
}
}
func Address(ip int32, port uint16) string {
var s string
for i := 3; i >= 0; i-- {
x := byte(ip >> uint(i*8))
s += strconv.Itoa(int(x))
if i != 0 {
s += "."
}
}
s += ":" + strconv.Itoa(int(port))
return s
}
func compare(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func generateInfoHash(m *metadata.MetaInfo) ([]byte, error) {
s, err := bencode.Encode(m.Info)
if err != nil {
return nil, err
}
sha := sha1.New()
_, e := sha.Write([]byte(s))
if e != nil {
return nil, e
}
return sha.Sum(nil), nil
}
func generateRandomPeerId() ([]byte, error) {
hash := sha1.New()
str := ""
i := rand.Int() % 10
for ; i > 0; i-- {
str += string(byte(rand.Int()))
}
_, e := hash.Write([]byte(str))
if e != nil {
return nil, e
}
return hash.Sum(nil), nil
}
func intToStr(size int) string {
if size >= MB {
return fmt.Sprintf("%4.2fMB", float32(float32(size)/float32(MB)))
} else if size >= KB {
return fmt.Sprintf("%4.2fKB", float32(float32(size)/float32(KB)))
} else {
return fmt.Sprintf("%d Bs", size)
}
}