fedilogue/fedictl/uniquefifo.go

83 lines
1.2 KiB
Go
Raw Normal View History

2021-02-03 00:07:51 +00:00
package main
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)
//logDebug.Print("Condition 1 for ", v)
ret = false
} else {
i := q.Contains(v)
if i != -1 {
q.Remove(i)
//logDebug.Print("Condition 2 for ", v)
ret = true
} else {
//logDebug.Print("Condition 3 for ", v)
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
}
/*
func main() {
u := newUniqueFifo(3)
u.Add("First")
u.Add("First")
fmt.Println(u)
u.Add("Second")
fmt.Println(u)
u.Add("First")
fmt.Println(u)
u.Add("Third")
fmt.Println(u)
u.Add("Fourth")
fmt.Println(u)
}
*/