github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/render/string_map.go (about)

     1  package render
     2  
     3  import (
     4  	"sort"
     5  	"sync"
     6  )
     7  
     8  // stringMap wraps sync.Map and uses the following types:
     9  // key:   string
    10  // value: string
    11  type stringMap struct {
    12  	data sync.Map
    13  }
    14  
    15  // Delete the key from the map
    16  func (m *stringMap) Delete(key string) {
    17  	m.data.Delete(key)
    18  }
    19  
    20  // Load the key from the map.
    21  // Returns string or bool.
    22  // A false return indicates either the key was not found
    23  // or the value is not of type string
    24  func (m *stringMap) Load(key string) (string, bool) {
    25  	i, ok := m.data.Load(key)
    26  	if !ok {
    27  		return ``, false
    28  	}
    29  	s, ok := i.(string)
    30  	return s, ok
    31  }
    32  
    33  // LoadOrStore will return an existing key or
    34  // store the value if not already in the map
    35  func (m *stringMap) LoadOrStore(key string, value string) (string, bool) {
    36  	i, _ := m.data.LoadOrStore(key, value)
    37  	s, ok := i.(string)
    38  	return s, ok
    39  }
    40  
    41  // Range over the string values in the map
    42  func (m *stringMap) Range(f func(key string, value string) bool) {
    43  	m.data.Range(func(k, v interface{}) bool {
    44  		key, ok := k.(string)
    45  		if !ok {
    46  			return false
    47  		}
    48  		value, ok := v.(string)
    49  		if !ok {
    50  			return false
    51  		}
    52  		return f(key, value)
    53  	})
    54  }
    55  
    56  // Store a string in the map
    57  func (m *stringMap) Store(key string, value string) {
    58  	m.data.Store(key, value)
    59  }
    60  
    61  // Keys returns a list of keys in the map
    62  func (m *stringMap) Keys() []string {
    63  	var keys []string
    64  	m.Range(func(key string, value string) bool {
    65  		keys = append(keys, key)
    66  		return true
    67  	})
    68  	sort.Strings(keys)
    69  	return keys
    70  }