github.com/uber-go/tally/v4@v4.1.17/internal/cache/string_intern.go (about)

     1  // Copyright (c) 2021 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package cache
    22  
    23  import (
    24  	"sync"
    25  )
    26  
    27  // StringInterner interns strings.
    28  type StringInterner struct {
    29  	entries map[string]string
    30  	mtx     sync.RWMutex
    31  }
    32  
    33  // NewStringInterner creates a new StringInterner.
    34  func NewStringInterner() *StringInterner {
    35  	return &StringInterner{
    36  		entries: make(map[string]string),
    37  	}
    38  }
    39  
    40  // Intern interns s.
    41  func (i *StringInterner) Intern(s string) string {
    42  	i.mtx.RLock()
    43  	x, ok := i.entries[s]
    44  	i.mtx.RUnlock()
    45  
    46  	if ok {
    47  		return x
    48  	}
    49  
    50  	i.mtx.Lock()
    51  	i.entries[s] = s
    52  	i.mtx.Unlock()
    53  
    54  	return s
    55  }