Source file src/maps/maps.go

     1  // Copyright 2021 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  // Package maps defines various functions useful with maps of any type.
     6  package maps
     7  
     8  import (
     9  	_ "unsafe"
    10  )
    11  
    12  // Equal reports whether two maps contain the same key/value pairs.
    13  // Values are compared using ==.
    14  func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
    15  	if len(m1) != len(m2) {
    16  		return false
    17  	}
    18  	for k, v1 := range m1 {
    19  		if v2, ok := m2[k]; !ok || v1 != v2 {
    20  			return false
    21  		}
    22  	}
    23  	return true
    24  }
    25  
    26  // EqualFunc is like Equal, but compares values using eq.
    27  // Keys are still compared with ==.
    28  func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool {
    29  	if len(m1) != len(m2) {
    30  		return false
    31  	}
    32  	for k, v1 := range m1 {
    33  		if v2, ok := m2[k]; !ok || !eq(v1, v2) {
    34  			return false
    35  		}
    36  	}
    37  	return true
    38  }
    39  
    40  // clone is implemented in the runtime package.
    41  //
    42  //go:linkname clone maps.clone
    43  func clone(m any) any
    44  
    45  // Clone returns a copy of m.  This is a shallow clone:
    46  // the new keys and values are set using ordinary assignment.
    47  func Clone[M ~map[K]V, K comparable, V any](m M) M {
    48  	// Preserve nil in case it matters.
    49  	if m == nil {
    50  		return nil
    51  	}
    52  	return clone(m).(M)
    53  }
    54  
    55  // Copy copies all key/value pairs in src adding them to dst.
    56  // When a key in src is already present in dst,
    57  // the value in dst will be overwritten by the value associated
    58  // with the key in src.
    59  func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
    60  	for k, v := range src {
    61  		dst[k] = v
    62  	}
    63  }
    64  
    65  // DeleteFunc deletes any key/value pairs from m for which del returns true.
    66  func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
    67  	for k, v := range m {
    68  		if del(k, v) {
    69  			delete(m, k)
    70  		}
    71  	}
    72  }
    73  

View as plain text