ring.go
657 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package util
import (
"container/list"
"sync"
)
type Ring struct {
sync.Mutex
*list.List
capacity int
}
func NewRing(capacity int) *Ring {
return &Ring{capacity: capacity, List: list.New()}
}
func (r *Ring) Add(item interface{}) interface{} {
r.Lock()
defer r.Unlock()
// add new item
r.PushFront(item)
// remove old item if at capacity
var old interface{}
if r.Len() >= r.capacity {
old = r.Remove(r.Back())
}
return old
}
func (r *Ring) Slice() []interface{} {
r.Lock()
defer r.Unlock()
i := 0
items := make([]interface{}, r.Len())
for e := r.Front(); e != nil; e = e.Next() {
items[i] = e.Value
i++
}
return items
}