Update link to codesearch tools (#93)
[debiancodesearch.git] / stringpool / stringpool.go
blob7c1c88a78a4f6bdb0ee172ff54e09c691bdf9362
1 // stringpool provides a pool of string pointers, ensuring that each string is
2 // stored only once in memory. This is useful for queries that have many
3 // results, as the amount of source packages is limited. So, as soon as
4 // len(results) > len(sourcepackages), you save memory using a stringpool.
5 package stringpool
7 import (
8 "sync"
11 type StringPool struct {
12 sync.RWMutex
13 strings map[string]*string
16 func NewStringPool() *StringPool {
17 return &StringPool{
18 strings: make(map[string]*string)}
21 func (pool *StringPool) Get(s string) *string {
22 // Check if the entry is already in the pool with a slightly cheaper
23 // (read-only) mutex.
24 pool.RLock()
25 stored, ok := pool.strings[s]
26 pool.RUnlock()
27 if ok {
28 return stored
31 pool.Lock()
32 defer pool.Unlock()
33 stored, ok = pool.strings[s]
34 if ok {
35 return stored
37 pool.strings[s] = &s
38 return &s