Created
August 24, 2012 16:51
-
-
Save jordanorelli/3452801 to your computer and use it in GitHub Desktop.
fixed-size set in Go
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 { | |
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 | |
} |
ugh, serialized, that is.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.