Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created October 9, 2012 23:11
Show Gist options
  • Save jordanorelli/3862062 to your computer and use it in GitHub Desktop.
Save jordanorelli/3862062 to your computer and use it in GitHub Desktop.
a simple string cache
type idCache struct {
sync.RWMutex
data map[string]*string
maxSize int
newest *string
oldest *string
}
func newIdCache(size int) *idCache {
return &idCache{
data: make(map[string]*string, size),
maxSize: size,
newest: nil,
oldest: nil,
}
}
func (c *idCache) has(s string) bool {
c.RLock()
defer c.RUnlock()
_, haz := c.data[s]
return haz
}
func (c *idCache) add(s string) {
c.Lock()
defer c.Unlock()
if c.newest != nil {
c.data[*c.newest] = &s
}
c.newest = &s
if c.oldest == nil {
c.oldest = &s
}
for len(c.data) >= c.maxSize {
o := *c.oldest
c.oldest = c.data[o]
delete(c.data, o)
}
c.data[s] = nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment