v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/util/maps/keys.go (about) 1 package maps 2 3 import ( 4 "sort" 5 ) 6 7 type sortable interface { 8 ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64 | ~string 9 } 10 11 type sortableSlice[T sortable] []T 12 13 func (s sortableSlice[T]) Len() int { return len(s) } 14 func (s sortableSlice[T]) Less(i, j int) bool { return s[i] < s[j] } 15 func (s sortableSlice[T]) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 16 17 func Keys[K comparable, V any](m map[K]V) []K { 18 if m == nil { 19 return nil 20 } 21 22 keys := make([]K, len(m)) 23 if len(keys) == 0 { 24 return keys 25 } 26 27 var i int = len(m) - 1 28 for k := range m { 29 keys[i] = k 30 i-- 31 } 32 33 var zero K 34 switch any(&zero).(type) { 35 case *string: 36 sort.Strings(*any(&keys).(*[]string)) 37 case *int: 38 sort.Ints(*any(&keys).(*[]int)) 39 case *float64: 40 sort.Float64s(*any(&keys).(*[]float64)) 41 case *uint: 42 sort.Sort(sortableSlice[uint](*any(&keys).(*[]uint))) 43 case *uint8: 44 sort.Sort(sortableSlice[uint8](*any(&keys).(*[]uint8))) 45 case *uint16: 46 sort.Sort(sortableSlice[uint16](*any(&keys).(*[]uint16))) 47 case *uint32: 48 sort.Sort(sortableSlice[uint32](*any(&keys).(*[]uint32))) 49 case *uint64: 50 sort.Sort(sortableSlice[uint64](*any(&keys).(*[]uint64))) 51 case *uintptr: 52 sort.Sort(sortableSlice[uintptr](*any(&keys).(*[]uintptr))) 53 case *int8: 54 sort.Sort(sortableSlice[int8](*any(&keys).(*[]int8))) 55 case *int16: 56 sort.Sort(sortableSlice[int16](*any(&keys).(*[]int16))) 57 case *int32: 58 sort.Sort(sortableSlice[int32](*any(&keys).(*[]int32))) 59 case *int64: 60 sort.Sort(sortableSlice[int64](*any(&keys).(*[]int64))) 61 case *float32: 62 sort.Sort(sortableSlice[float32](*any(&keys).(*[]float32))) 63 } 64 65 return keys 66 }