Skip to content

Instantly share code, notes, and snippets.

@CAFxX
Forked from karlseguin/intern.go
Last active September 26, 2018 01:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CAFxX/6467c15e6fa3ac0fd6480df2273414a4 to your computer and use it in GitHub Desktop.
Save CAFxX/6467c15e6fa3ac0fd6480df2273414a4 to your computer and use it in GitHub Desktop.
String interning in Golang
package intern
import (
"sync"
)
type Pool struct {
sync.RWMutex
lookup map[string]string
}
func New() *Pool {
return &Pool{lookup: make(map[string]string)}
}
func (p *Pool) Intern(s string) string {
p.RLock()
ss, found := p.lookup[s]
p.RUnlock()
if found {
return ss
}
/*
if we had p.RLockToLock() - i.e. something that either atomically upgrades the
RLock to a Lock and returns true or does RUnlock+Lock and returns false - we
could do this instead of the following:
if !p.RLockToLock() {
ss, found := p.lookup[s]
if found {
s = ss
goto unlock_and_return
}
}
p.Lookup[s] = s
unlock_and_return:
p.Unlock()
return s
*/
p.Lock()
ss, found := p.lookup[s]
if !found {
p.lookup[s] = s
ss = s
}
p.Unlock()
return ss
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment