Skip to content

Instantly share code, notes, and snippets.

@marz619
Created September 14, 2017 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marz619/7aa4422c175529b5af49289f0e9234b3 to your computer and use it in GitHub Desktop.
Save marz619/7aa4422c175529b5af49289f0e9234b3 to your computer and use it in GitHub Desktop.
Simple in memory Tristate (miss/yes/no) cache
package tristate
import "sync"
// State for a tristate cache
type State int
// cache State contants
const (
Miss State = iota
Yes
No
)
// Cache interface that satisfies the conditions
// of a tri-state (Miss/Yes/No)
type Cache interface {
Get(key interface{}) State
SetYes(keys ...interface{})
SetNo(keys ...interface{})
}
// NewCache returns a tristate cache
func NewCache(n int) Cache {
return &triStateCache{
m: sync.RWMutex{},
cache: make(map[interface{}]State, n),
}
}
// triStateCache is a simple yes/no/miss im memory cache
type triStateCache struct {
m sync.RWMutex
cache map[interface{}]State
}
// is it in the cache
func (tsc *triStateCache) Get(id interface{}) State {
tsc.m.RLock()
defer tsc.m.RUnlock()
if _, ok := tsc.cache[id]; !ok {
return Miss
}
return tsc.cache[id]
}
func (tsc *triStateCache) SetYes(ids ...interface{}) {
tsc.m.Lock()
defer tsc.m.Unlock()
for _, i := range ids {
tsc.cache[i] = Yes
}
}
func (tsc *triStateCache) SetNo(ids ...interface{}) {
tsc.m.Lock()
defer tsc.m.Unlock()
for _, i := range ids {
tsc.cache[i] = No
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment