File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -49,7 +49,33 @@ func (tc *TimeCache) Add(item string) bool {
4949 return false
5050 }
5151
52- // sweep old entries (those for which caching timespan has passed)
52+ tc .sweep ()
53+
54+ tc .cache [item ] = time .Now ()
55+ tc .indexer .PushFront (item )
56+ return true
57+ }
58+
59+ // Has checks presence of an entry in the cache. Returns `true` if entry is
60+ // present and `false` otherwise.
61+ func (tc * TimeCache ) Has (item string ) bool {
62+ tc .mutex .RLock ()
63+ defer tc .mutex .RUnlock ()
64+
65+ _ , ok := tc .cache [item ]
66+ return ok
67+ }
68+
69+ // Sweep removes old entries. That is those for which caching timespan has
70+ // passed.
71+ func (tc * TimeCache ) Sweep () {
72+ tc .mutex .Lock ()
73+ defer tc .mutex .Unlock ()
74+
75+ tc .sweep ()
76+ }
77+
78+ func (tc * TimeCache ) sweep () {
5379 for {
5480 back := tc .indexer .Back ()
5581 if back == nil {
@@ -73,18 +99,4 @@ func (tc *TimeCache) Add(item string) bool {
7399 break
74100 }
75101 }
76-
77- tc .cache [item ] = time .Now ()
78- tc .indexer .PushFront (item )
79- return true
80- }
81-
82- // Has checks presence of an entry in the cache. Returns `true` if entry is
83- // present and `false` otherwise.
84- func (tc * TimeCache ) Has (item string ) bool {
85- tc .mutex .RLock ()
86- defer tc .mutex .RUnlock ()
87-
88- _ , ok := tc .cache [item ]
89- return ok
90102}
Original file line number Diff line number Diff line change @@ -47,6 +47,23 @@ func TestExpiration(t *testing.T) {
4747 }
4848
4949 if cache .Has (strconv .Itoa (0 )) {
50- t .Fatal ("should have dropped '0' key from the cache already" )
50+ t .Fatal ("should have dropped '0' key from the cache" )
51+ }
52+ }
53+
54+ func TestSweep (t * testing.T ) {
55+ cache := NewTimeCache (500 * time .Millisecond )
56+ cache .Add ("old" )
57+ time .Sleep (100 * time .Millisecond )
58+ cache .Add ("new" )
59+ time .Sleep (400 * time .Millisecond )
60+
61+ cache .Sweep ()
62+
63+ if cache .Has ("old" ) {
64+ t .Fatal ("should have dropped 'old' key from the cache" )
65+ }
66+ if ! cache .Has ("new" ) {
67+ t .Fatal ("should still have 'new' in the cache" )
5168 }
5269}
You can’t perform that action at this time.
0 commit comments