fedilogue/shared/uniquefifo.go

63 lines
926 B
Go
Raw Normal View History

2021-09-29 02:47:10 +00:00
package shared
import (
"sync"
)
type UniqueFifo struct {
slice []string
Mu sync.Mutex
size int
}
func NewUniqueFifo(size int) *UniqueFifo {
q := UniqueFifo{}
q.slice = make([]string, 0)
q.size = size
return &q
}
func (q *UniqueFifo) Add(v string) bool {
ret := false
if len(q.slice) == 0 {
q.slice = append(q.slice, v)
ret = false
} else {
i := q.Contains(v)
if i != -1 {
q.Remove(i)
ret = true
} else {
ret = false
}
q.slice = append(q.slice, "")
copy(q.slice[1:], q.slice)
q.slice[0] = v
if len(q.slice) <= q.size {
q.slice = q.slice[:len(q.slice)]
} else {
q.slice = q.slice[:q.size]
}
}
return ret
}
func (q *UniqueFifo) Remove(r int) {
f := q.slice[:r]
e := q.slice[r+1:]
q.slice = f
q.slice = append(q.slice, e...)
}
func (q *UniqueFifo) Contains(v string) int {
for i, val := range q.slice {
if val == v {
return i
}
}
return -1
}