golang.org/x/tools/gopls@v0.15.3/internal/util/immutable/immutable.go (about)

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // The immutable package defines immutable wrappers around common data
     6  // structures. These are used for additional type safety inside gopls.
     7  //
     8  // See the "persistent" package for copy-on-write data structures.
     9  package immutable
    10  
    11  // Map is an immutable wrapper around an ordinary Go map.
    12  type Map[K comparable, V any] struct {
    13  	m map[K]V
    14  }
    15  
    16  // MapOf wraps the given Go map.
    17  //
    18  // The caller must not subsequently mutate the map.
    19  func MapOf[K comparable, V any](m map[K]V) Map[K, V] {
    20  	return Map[K, V]{m}
    21  }
    22  
    23  // Value returns the mapped value for k.
    24  // It is equivalent to the commaok form of an ordinary go map, and returns
    25  // (zero, false) if the key is not present.
    26  func (m Map[K, V]) Value(k K) (V, bool) {
    27  	v, ok := m.m[k]
    28  	return v, ok
    29  }
    30  
    31  // Len returns the number of entries in the Map.
    32  func (m Map[K, V]) Len() int {
    33  	return len(m.m)
    34  }
    35  
    36  // Range calls f for each mapped (key, value) pair.
    37  // There is no way to break out of the loop.
    38  // TODO: generalize when Go iterators (#61405) land.
    39  func (m Map[K, V]) Range(f func(k K, v V)) {
    40  	for k, v := range m.m {
    41  		f(k, v)
    42  	}
    43  }