Skip to content

Commit

Permalink
Implement cleanup and timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
acoshift committed Jan 4, 2017
1 parent 2c53e4e commit 9aea6ce
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
22 changes: 22 additions & 0 deletions gotcha.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,28 @@ func (g *Gotcha) Expired(index interface{}) bool {
return it != nil && expired(it)
}

// Cleanup removes all expired data
func (g *Gotcha) Cleanup() {
g.m.Lock()
defer g.m.Unlock()
for index, it := range g.d {
if expired(it) {
delete(g.d, index)
}
}
}

// Timestamp returns timestamp of an index
func (g *Gotcha) Timestamp(index interface{}) *time.Time {
g.m.RLock()
defer g.m.RUnlock()
it := g.d[index]
if it == nil {
return nil
}
return &it.ts
}

// helper funcitons
func expired(it *item) bool {
if it.ttl <= 0 {
Expand Down
27 changes: 27 additions & 0 deletions gotcha_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,30 @@ func TestExpired(t *testing.T) {
t.Errorf("expected 1 expired")
}
}

func TestCleanup(t *testing.T) {
g := New()
g.SetTTL(1, 2, time.Millisecond*10)
g.SetTTL(2, 3, time.Millisecond*20)
time.Sleep(time.Millisecond * 15)
g.Cleanup()
if g.Exists(1) {
t.Errorf("expected 1 not exists")
}
if !g.Exists(2) {
t.Errorf("expected 2 exists")
}
}

func TestTimestamp(t *testing.T) {
g := New()
g.SetTTL(1, 2, time.Millisecond*10)
ts := g.Timestamp(1)
if ts == nil {
t.Errorf("expected timestamp not nil")
}
ts = g.Timestamp(2)
if ts != nil {
t.Errorf("expected timestamp to be nil")
}
}

0 comments on commit 9aea6ce

Please sign in to comment.