Created
October 9, 2012 23:11
-
-
Save jordanorelli/3862062 to your computer and use it in GitHub Desktop.
a simple string 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
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