-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixedlist.go
More file actions
56 lines (49 loc) · 893 Bytes
/
fixedlist.go
File metadata and controls
56 lines (49 loc) · 893 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
47
48
49
50
51
52
53
54
55
56
package fixedlist
import (
"container/list"
"sync"
)
type FixedList interface {
Add(interface{})
Len() int
Data() []interface{}
}
type fixedList struct {
sync.RWMutex
length int
data *list.List
}
//创建定长列表
func NewFixedList(len int) FixedList {
f := &fixedList{}
f.length = len
f.data = list.New()
return f
}
//添加一条记录
func (f *fixedList) Add(val interface{}) {
f.Lock()
defer f.Unlock()
f.data.PushBack(val)
if f.data.Len() > f.length {
for i := 0; i <= f.data.Len()-f.length; i++ {
f.data.Remove(f.data.Front())
}
}
}
//获取数据长度
func (f *fixedList) Len() int {
f.RLock()
defer f.RUnlock()
return f.data.Len()
}
//获取数据
func (f *fixedList) Data() []interface{} {
f.RLock()
defer f.RUnlock()
var data []interface{}
for i := f.data.Front(); i != nil; i = i.Next() {
data = append(data, i.Value)
}
return data
}