github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/sync/loadingcache/map.go (about)

     1  package loadingcache
     2  
     3  import "sync"
     4  
     5  // Map is a keyed collection of Values. Map{} is ready to use.
     6  // (*Map)(nil) is valid and never caches or shares results for any key.
     7  // Maps are concurrency-safe. They must not be copied.
     8  //
     9  // Implementation notes:
    10  //
    11  // Compared to sync.Map, this Map is not sophisticated in terms of optimizing for high concurrency
    12  // with disjoint sets of keys. It could probably be improved.
    13  //
    14  // Loading on-demand, without repeated value computation, is reminiscent of Guava's LoadingCache:
    15  // https://github.com/google/guava/wiki/CachesExplained
    16  type Map struct {
    17  	mu sync.Mutex
    18  	m  map[interface{}]*Value
    19  }
    20  
    21  // GetOrCreate returns an existing or new Value associated with key.
    22  // Note: If m == nil, returns nil, a never-caching Value.
    23  func (m *Map) GetOrCreate(key interface{}) *Value {
    24  	if m == nil {
    25  		return nil
    26  	}
    27  	m.mu.Lock()
    28  	defer m.mu.Unlock()
    29  	if m.m == nil {
    30  		m.m = make(map[interface{}]*Value)
    31  	}
    32  	if _, ok := m.m[key]; !ok {
    33  		m.m[key] = new(Value)
    34  	}
    35  	return m.m[key]
    36  }
    37  
    38  func (m *Map) DeleteAll() {
    39  	m.mu.Lock()
    40  	defer m.mu.Unlock()
    41  	m.m = nil
    42  }