decred.org/dcrdex@v1.0.3/dex/utils/generics.go (about)

     1  // This code is available on the terms of the project LICENSE.md file,
     2  // also available online at https://blueoakcouncil.org/license/1.0.0.
     3  
     4  package utils
     5  
     6  import "golang.org/x/exp/constraints"
     7  
     8  func ReverseSlice[T any](s []T) {
     9  	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    10  		s[i], s[j] = s[j], s[i]
    11  	}
    12  }
    13  
    14  func CopyMap[K comparable, V any](m map[K]V) map[K]V {
    15  	r := make(map[K]V, len(m))
    16  	for k, v := range m {
    17  		r[k] = v
    18  	}
    19  	return r
    20  }
    21  
    22  func MapItems[K comparable, V any](m map[K]V) []V {
    23  	vs := make([]V, 0, len(m))
    24  	for _, v := range m {
    25  		vs = append(vs, v)
    26  	}
    27  	return vs
    28  }
    29  
    30  func MapKeys[K comparable, V any](m map[K]V) []K {
    31  	ks := make([]K, 0, len(m))
    32  	for k := range m {
    33  		ks = append(ks, k)
    34  	}
    35  	return ks
    36  }
    37  
    38  func SafeSub[I constraints.Unsigned](a I, b I) I {
    39  	if a < b {
    40  		return 0
    41  	}
    42  	return a - b
    43  }
    44  
    45  func Min[I constraints.Ordered](m I, ns ...I) I {
    46  	min := m
    47  	for _, n := range ns {
    48  		if n < min {
    49  			min = n
    50  		}
    51  	}
    52  	return min
    53  }
    54  
    55  func Max[I constraints.Ordered](m I, ns ...I) I {
    56  	max := m
    57  	for _, n := range ns {
    58  		if n > max {
    59  			max = n
    60  		}
    61  	}
    62  	return max
    63  }
    64  
    65  func Clamp[I constraints.Ordered](v I, min I, max I) I {
    66  	if v < min {
    67  		v = min
    68  	} else if v > max {
    69  		v = max
    70  	}
    71  	return v
    72  }