This repository has been archived by the owner on Apr 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
148 lines (124 loc) · 2.2 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
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
138
139
140
141
142
143
144
145
146
147
148
package taobao
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"sync"
"github.com/PuerkitoBio/goquery"
)
import "math/rand"
import crand "crypto/rand"
var (
pt = fmt.Printf
sp = fmt.Sprintf
fw = fmt.Fprintf
)
func dumpUrl(rawUrl string) {
u, err := url.Parse(rawUrl)
ce(err, "parse url")
query := u.Query()
var keys []string
for k := range query {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
pt("%s -> %v\n", k, query[k])
}
}
func dumpDoc(doc *goquery.Document) {
html, _ := doc.Html()
pt("%s\n", html)
}
func getBytes(client *http.Client, url string) (ret []byte, err error) {
defer ct(&err)
resp, err := client.Get(url)
ce(err, "get")
defer resp.Body.Close()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, resp.Body)
ce(err, "read")
return buf.Bytes(), nil
}
func lp() {
if p := recover(); p != nil {
pt("%v\n", p)
}
}
type Jobs []Job
func (s Jobs) Shuffle() {
for i := len(s) - 1; i >= 1; i-- {
j := rand.Intn(i + 1)
s[i], s[j] = s[j], s[i]
}
}
func init() {
var seed int64
binary.Read(crand.Reader, binary.LittleEndian, &seed)
rand.Seed(seed)
}
func (s Jobs) Sort(cmp func(a, b Job) bool) {
sorter := sliceSorter{
l: len(s),
less: func(i, j int) bool {
return cmp(s[i], s[j])
},
swap: func(i, j int) {
s[i], s[j] = s[j], s[i]
},
}
_ = sorter.Len
_ = sorter.Less
_ = sorter.Swap
sort.Sort(sorter)
}
type StrSet map[string]struct{}
func NewStrSet() StrSet {
return StrSet(make(map[string]struct{}))
}
func (s StrSet) Add(t string) {
s[t] = struct{}{}
}
func (s StrSet) Del(t string) {
delete(s, t)
}
func (s StrSet) Has(t string) (ok bool) {
_, ok = s[t]
return
}
func (s StrSet) Each(fn func(string)) {
for e := range s {
fn(e)
}
}
func (s StrSet) Slice() (ret []string) {
for e := range s {
ret = append(ret, e)
}
return
}
func withLock(l sync.Locker, fn func()) {
l.Lock()
fn()
l.Unlock()
}
type Ints []int
func (s Ints) Sort(cmp func(a, b int) bool) {
sorter := sliceSorter{
l: len(s),
less: func(i, j int) bool {
return cmp(s[i], s[j])
},
swap: func(i, j int) {
s[i], s[j] = s[j], s[i]
},
}
_ = sorter.Len
_ = sorter.Less
_ = sorter.Swap
sort.Sort(sorter)
}