ccache/bucket.go

54 lines
948 B
Go
Raw Normal View History

2013-10-19 02:56:28 +02:00
package ccache
import (
"sync"
"time"
2013-10-19 02:56:28 +02:00
)
type Bucket struct {
sync.RWMutex
lookup map[string]*Item
}
2013-10-19 14:36:33 +02:00
func (b *Bucket) get(key string) *Item {
2013-10-19 02:56:28 +02:00
b.RLock()
defer b.RUnlock()
return b.lookup[key]
}
func (b *Bucket) set(key string, value interface{}, duration time.Duration) *Item {
expires := time.Now().Add(duration)
2013-10-19 02:56:28 +02:00
b.Lock()
defer b.Unlock()
if existing, exists := b.lookup[key]; exists {
existing.Lock()
existing.value = value
existing.expires = expires
2013-10-19 02:56:28 +02:00
existing.Unlock()
return existing
}
item := newItem(key, value, expires)
2013-10-19 02:56:28 +02:00
b.lookup[key] = item
return item
}
func (b *Bucket) delete(key string) {
b.Lock()
defer b.Unlock()
delete(b.lookup, key)
}
2013-10-19 02:56:28 +02:00
func (b *Bucket) getAndDelete(key string) *Item{
2013-10-19 02:56:28 +02:00
b.Lock()
defer b.Unlock()
item := b.lookup[key]
2013-10-19 02:56:28 +02:00
delete(b.lookup, key)
return item
2013-10-19 02:56:28 +02:00
}
func (b *Bucket) clear() {
b.Lock()
defer b.Unlock()
b.lookup = make(map[string]*Item)
}