-
Notifications
You must be signed in to change notification settings - Fork 0
/
stale.go
67 lines (55 loc) · 1.17 KB
/
stale.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package kafkasource
import (
"sync"
"time"
)
type item struct {
object interface{}
added time.Time
}
// StaleList is a list of items that timeout lazily,
// only checking for item expiration when a new one is added.
//
// This should not be used for storing a big number of items.
type StaleList struct {
items []item
timeout time.Duration
m sync.Mutex
}
func NewStaleList(timeout time.Duration) *StaleList {
return &StaleList{
items: []item{},
timeout: timeout,
}
}
func (sl *StaleList) count() int {
index := -1
for i := range sl.items {
if time.Since(sl.items[i].added) > sl.timeout {
index = i
continue
}
break
}
if index != -1 {
sl.items = sl.items[index+1:]
}
return len(sl.items)
}
// AddAndCount adds a new element to the list and updates the count, removing
// any stale items from it.
func (sl *StaleList) AddAndCount(object interface{}) int {
sl.m.Lock()
defer sl.m.Unlock()
sl.items = append(sl.items, item{
added: time.Now(),
object: object,
})
return sl.count()
}
// Count updates the count removing any stale items from it.
func (sl *StaleList) Count() int {
sl.m.Lock()
defer sl.m.Unlock()
return sl.count()
}