Created
September 14, 2017 17:12
-
-
Save marz619/7aa4422c175529b5af49289f0e9234b3 to your computer and use it in GitHub Desktop.
Simple in memory Tristate (miss/yes/no) cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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