-
Notifications
You must be signed in to change notification settings - Fork 0
/
whowas.go
85 lines (75 loc) · 1.72 KB
/
whowas.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
// Copyright (c) 2012-2014 Jeremy Latt
// Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
type WhoWasList struct {
buffer []*WhoWas
start int
end int
}
type WhoWas struct {
nicknameCasefolded string
nickname string
username string
hostname string
realname string
}
func NewWhoWasList(size uint) *WhoWasList {
return &WhoWasList{
buffer: make([]*WhoWas, size+1),
}
}
func (list *WhoWasList) Append(client *Client) {
list.buffer[list.end] = &WhoWas{
nicknameCasefolded: client.nickCasefolded,
nickname: client.nick,
username: client.username,
hostname: client.hostname,
realname: client.realname,
}
list.end = (list.end + 1) % len(list.buffer)
if list.end == list.start {
list.start = (list.end + 1) % len(list.buffer)
}
}
func (list *WhoWasList) Find(nickname string, limit int64) []*WhoWas {
results := make([]*WhoWas, 0)
casefoldedNickname, err := CasefoldName(nickname)
if err != nil {
return results
}
for whoWas := range list.Each() {
if casefoldedNickname != whoWas.nicknameCasefolded {
continue
}
results = append(results, whoWas)
if int64(len(results)) >= limit {
break
}
}
return results
}
func (list *WhoWasList) prev(index int) int {
index -= 1
if index < 0 {
index += len(list.buffer)
}
return index
}
// Iterate the buffer in reverse.
func (list *WhoWasList) Each() <-chan *WhoWas {
ch := make(chan *WhoWas)
go func() {
defer close(ch)
if list.start == list.end {
return
}
start := list.prev(list.end)
end := list.prev(list.start)
for start != end {
ch <- list.buffer[start]
start = list.prev(start)
}
}()
return ch
}