decred.org/dcrdex@v1.0.5/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 Map[F any, T any](s []F, f func(F) T) []T {
    39  	r := make([]T, len(s))
    40  	for i, v := range s {
    41  		r[i] = f(v)
    42  	}
    43  	return r
    44  }
    45  
    46  func SafeSub[I constraints.Unsigned](a I, b I) I {
    47  	if a < b {
    48  		return 0
    49  	}
    50  	return a - b
    51  }
    52  
    53  func Min[I constraints.Ordered](m I, ns ...I) I {
    54  	min := m
    55  	for _, n := range ns {
    56  		if n < min {
    57  			min = n
    58  		}
    59  	}
    60  	return min
    61  }
    62  
    63  func Max[I constraints.Ordered](m I, ns ...I) I {
    64  	max := m
    65  	for _, n := range ns {
    66  		if n > max {
    67  			max = n
    68  		}
    69  	}
    70  	return max
    71  }
    72  
    73  func Clamp[I constraints.Ordered](v I, min I, max I) I {
    74  	if v < min {
    75  		v = min
    76  	} else if v > max {
    77  		v = max
    78  	}
    79  	return v
    80  }