-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathttlcache.go
More file actions
84 lines (77 loc) · 2 KB
/
Copy pathttlcache.go
File metadata and controls
84 lines (77 loc) · 2 KB
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
package main
import (
"errors"
//"fmt"
"math/rand"
"time"
)
// TTL Map, type as map[uint64]*Update
type TtlCache struct {
TtlList []*Update
Pointer int
RandGen *rand.Rand
}
// Return a new TTL Map
func NewTtlCache() *TtlCache {
// Source for genearting random number
randSource := rand.NewSource(time.Now().UnixNano())
randGen := rand.New(randSource)
ttllist := make([]*Update, 0)
Logger.Debug("TTL cache created\n")
ttlcache := TtlCache{ttllist, 0, randGen}
return &ttlcache
}
// Set the update packet in TTL Cache
func (tc *TtlCache) Set(val *Update) {
if val.TTL < 1 {
Logger.Debug("TTL cache cannot set for ttl=0 %d\n", val.UpdateID)
return
}
tc.TtlList = append(tc.TtlList, val)
Logger.Debug("TTL cache add a new update ID: %d, TTL: %d\n", val.UpdateID, val.TTL)
}
// Get one entry each time in TTL Cache
func (tc *TtlCache) Get() (*Update, error) {
if len(tc.TtlList) == 0 {
Logger.Debug("TTL cache empty\n")
return nil, errors.New("Empty TTL List, cannot Get()")
}
cur := tc.TtlList[tc.Pointer]
// Copy current update
update := Update{cur.UpdateID, cur.TTL, cur.UpdateType, cur.MemberTimeStamp, cur.MemberIP, cur.MemberState}
cur.TTL -= 1
if cur.TTL < 1 {
Logger.Debug("TTL cache expired %d\n", cur.UpdateID)
// Delete this entry
copy(tc.TtlList[tc.Pointer:], tc.TtlList[tc.Pointer+1:])
tc.TtlList[len(tc.TtlList)-1] = nil
tc.TtlList = tc.TtlList[:len(tc.TtlList)-1]
}
if len(tc.TtlList) != 0 {
tc.Pointer = (tc.Pointer + 1) % len(tc.TtlList)
} else {
tc.Pointer = 0
}
return &update, nil
}
/*func main() {*/
//tc := NewTtlCache()
//u1 := Update{0, 3}
//tc.Set(&u1)
//tc.Set(&Update{0, 3})
//fmt.Println(len(tc.TtlList))
//u, err := tc.Get()
//fmt.Println(len(tc.TtlList), u.UpdateID)
//u, err = tc.Get()
//fmt.Println(len(tc.TtlList), u.UpdateID)
//u, err = tc.Get()
//fmt.Println(len(tc.TtlList), u.UpdateID)
//if err != nil {
//fmt.Println("ERR ", err)
//}
//u, err = tc.Get()
//fmt.Println(len(tc.TtlList), u.UpdateID)
//if err != nil {
//fmt.Println("ERR ", err)
//}
/*}*/