fedilogue/shared/uniquefifo.go

74 lines
1.3 KiB
Go
Raw Normal View History

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