ssh-chat/history.go

55 lines
817 B
Go
Raw Normal View History

2014-12-12 07:10:06 +01:00
// TODO: Split this out into its own module, it's kinda neat.
2014-12-12 07:03:32 +01:00
package main
2014-12-12 10:15:58 +01:00
import "sync"
2014-12-12 07:03:32 +01:00
type History struct {
entries []string
head int
size int
2014-12-12 10:15:58 +01:00
lock sync.Mutex
2014-12-12 07:03:32 +01:00
}
func NewHistory(size int) *History {
return &History{
entries: make([]string, size),
}
}
func (h *History) Add(entry string) {
2014-12-12 10:15:58 +01:00
h.lock.Lock()
defer h.lock.Unlock()
2014-12-12 07:03:32 +01:00
max := cap(h.entries)
h.head = (h.head + 1) % max
h.entries[h.head] = entry
if h.size < max {
h.size++
}
}
func (h *History) Len() int {
return h.size
}
func (h *History) Get(num int) []string {
2014-12-12 10:15:58 +01:00
h.lock.Lock()
defer h.lock.Unlock()
2014-12-12 07:03:32 +01:00
max := cap(h.entries)
if num > h.size {
num = h.size
}
r := make([]string, num)
for i := 0; i < num; i++ {
idx := (h.head - i) % max
if idx < 0 {
idx += max
}
r[num-i-1] = h.entries[idx]
}
return r
}