-
Notifications
You must be signed in to change notification settings - Fork 0
/
rolling_index_map.go
88 lines (76 loc) · 2.08 KB
/
rolling_index_map.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package common
import (
"fmt"
"github.com/bolaxy/errors"
)
// RollingIndexMap ...
type RollingIndexMap struct {
name string
size int
keys []uint32
mapping map[uint32]*RollingIndex
}
// NewRollingIndexMap ...
func NewRollingIndexMap(name string, size int) *RollingIndexMap {
return &RollingIndexMap{
name: name,
size: size,
keys: []uint32{},
mapping: make(map[uint32]*RollingIndex),
}
}
// AddKey ...
func (rim *RollingIndexMap) AddKey(key uint32) error {
if _, ok := rim.mapping[key]; ok {
return errors.NewStoreErr(rim.name, errors.KeyAlreadyExists, fmt.Sprint(key))
}
rim.keys = append(rim.keys, key)
rim.mapping[key] = NewRollingIndex(fmt.Sprintf("%s[%d]", rim.name, key), rim.size)
return nil
}
//Get return key items with index > skip
func (rim *RollingIndexMap) Get(key uint32, skipIndex int) ([]interface{}, error) {
items, ok := rim.mapping[key]
if !ok {
return nil, errors.NewStoreErr(rim.name, errors.KeyNotFound, fmt.Sprint(key))
}
cached, err := items.Get(skipIndex)
if err != nil {
return nil, err
}
return cached, nil
}
// GetItem ...
func (rim *RollingIndexMap) GetItem(key uint32, index int) (interface{}, error) {
return rim.mapping[key].GetItem(index)
}
// GetLast ...
func (rim *RollingIndexMap) GetLast(key uint32) (interface{}, error) {
pe, ok := rim.mapping[key]
if !ok {
return nil, errors.NewStoreErr(rim.name, errors.KeyNotFound, fmt.Sprint(key))
}
cached, _ := pe.GetLastWindow()
if len(cached) == 0 {
return "", errors.NewStoreErr(rim.name, errors.Empty, fmt.Sprint(key))
}
return cached[len(cached)-1], nil
}
// Set ...
func (rim *RollingIndexMap) Set(key uint32, item interface{}, index int) error {
items, ok := rim.mapping[key]
if !ok {
items = NewRollingIndex(fmt.Sprintf("%s[%d]", rim.name, key), rim.size)
rim.mapping[key] = items
}
return items.Set(item, index)
}
//Known returns [key] => lastKnownIndex
func (rim *RollingIndexMap) Known() map[uint32]int {
known := make(map[uint32]int)
for k, items := range rim.mapping {
_, lastIndex := items.GetLastWindow()
known[k] = lastIndex
}
return known
}