3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-25 21:39:25 +01:00
ergo/irc/whowas.go

94 lines
2.0 KiB
Go
Raw Normal View History

// Copyright (c) 2012-2014 Jeremy Latt
2017-03-27 14:15:02 +02:00
// Copyright (c) 2016 Daniel Oaks <daniel@danieloaks.net>
// released under the MIT license
package irc
2017-04-18 14:26:01 +02:00
import (
"sync"
)
// WhoWasList holds our list of prior clients (for use with the WHOWAS command).
type WhoWasList struct {
2018-05-04 06:24:54 +02:00
buffer []WhoWas
// three possible states:
// empty: start == end == -1
// partially full: start != end
// full: start == end > 0
// if entries exist, they go from `start` to `(end - 1) % length`
start int
end int
2017-04-18 14:26:01 +02:00
2018-05-04 06:24:54 +02:00
accessMutex sync.RWMutex // tier 1
}
// NewWhoWasList returns a new WhoWasList
2019-03-12 00:24:45 +01:00
func (list *WhoWasList) Initialize(size int) {
list.buffer = make([]WhoWas, size)
list.start = -1
list.end = -1
}
// Append adds an entry to the WhoWasList.
2018-05-04 06:24:54 +02:00
func (list *WhoWasList) Append(whowas WhoWas) {
2017-04-18 14:26:01 +02:00
list.accessMutex.Lock()
defer list.accessMutex.Unlock()
2018-05-04 06:24:54 +02:00
if len(list.buffer) == 0 {
return
}
2018-05-04 06:24:54 +02:00
var pos int
if list.start == -1 { // empty
pos = 0
list.start = 0
list.end = 1
} else if list.start != list.end { // partially full
pos = list.end
list.end = (list.end + 1) % len(list.buffer)
} else if list.start == list.end { // full
pos = list.end
list.end = (list.end + 1) % len(list.buffer)
list.start = list.end // advance start as well, overwriting first entry
}
2018-05-04 06:24:54 +02:00
list.buffer[pos] = whowas
}
// Find tries to find an entry in our WhoWasList with the given details.
2018-05-04 06:24:54 +02:00
func (list *WhoWasList) Find(nickname string, limit int) (results []WhoWas) {
casefoldedNickname, err := CasefoldName(nickname)
if err != nil {
2018-05-04 06:24:54 +02:00
return
}
2018-05-04 06:24:54 +02:00
list.accessMutex.RLock()
defer list.accessMutex.RUnlock()
if list.start == -1 {
return
}
// iterate backwards through the ring buffer
pos := list.prev(list.end)
for limit == 0 || len(results) < limit {
if casefoldedNickname == list.buffer[pos].nickCasefolded {
2018-05-04 06:24:54 +02:00
results = append(results, list.buffer[pos])
}
2018-05-04 06:24:54 +02:00
if pos == list.start {
break
}
2018-05-04 06:24:54 +02:00
pos = list.prev(pos)
}
2018-05-04 06:24:54 +02:00
return
}
2014-04-10 20:53:34 +02:00
func (list *WhoWasList) prev(index int) int {
2018-05-04 06:24:54 +02:00
switch index {
case 0:
return len(list.buffer) - 1
default:
return index - 1
}
}