Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created August 24, 2012 16:51
Show Gist options
  • Save jordanorelli/3452801 to your computer and use it in GitHub Desktop.
Save jordanorelli/3452801 to your computer and use it in GitHub Desktop.
fixed-size set in Go
type idCache struct {
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 {
_, haz := c.data[s]
return haz
}
func (c *idCache)add(s string) {
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
}
@jordanorelli
Copy link
Author

note: this isn't threadsafe. You'll need to toss in a sync.RWMutex to make it threadsafe. In my application, the things I'm de-duping come off a channel so they're already seriealized so I don't bother.

@jordanorelli
Copy link
Author

ugh, serialized, that is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment