-
-
Save CAFxX/6467c15e6fa3ac0fd6480df2273414a4 to your computer and use it in GitHub Desktop.
String interning in Golang
This file contains 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
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