github.com/puellanivis/breton@v0.2.16/lib/sort/search.go (about) 1 package sort 2 3 import ( 4 "sort" 5 ) 6 7 // Comparer defines a set of Comparison functions that will return <0 for i<j, ==0 for i==j, and >0 for i>j. 8 type Comparer interface { 9 Compare(i, j int) int 10 CompareFunc(x interface{}) func(int) int 11 } 12 13 // Search returns sort.Search(n, f) 14 func Search(n int, f func(int) bool) int { 15 return sort.Search(n, f) 16 } 17 18 // SearchFor takes arbitrary arguments, and attempts to find x as an element of a. 19 // 20 // If a implements `interface{ SearchFor(x interface{}) int }` the results of calling this method are returned. 21 // If a is a Comparer this is used as the function of sort.Search. 22 // All basic slices of types supported by this packager are also accepted. 23 func SearchFor(a interface{}, x interface{}) int { 24 type searcherFor interface { 25 SearchFor(x interface{}) int 26 } 27 28 type comparer interface { 29 Len() int 30 Comparer 31 } 32 33 switch a := a.(type) { 34 case searcherFor: 35 return a.SearchFor(x) 36 37 case comparer: 38 f := a.CompareFunc(x) 39 return sort.Search(a.Len(), func(i int) bool { return f(i) >= 0 }) 40 41 case []uint: 42 return SearchUints(a, x.(uint)) 43 case []uint8: 44 return SearchUint8s(a, x.(uint8)) 45 case []uint16: 46 return SearchUint16s(a, x.(uint16)) 47 case []uint32: 48 return SearchUint32s(a, x.(uint32)) 49 case []uint64: 50 return SearchUint64s(a, x.(uint64)) 51 52 case []int: 53 return SearchInts(a, x.(int)) 54 case []int8: 55 return SearchInt8s(a, x.(int8)) 56 case []int16: 57 return SearchInt16s(a, x.(int16)) 58 case []int32: 59 return SearchInt32s(a, x.(int32)) 60 case []int64: 61 return SearchInt64s(a, x.(int64)) 62 63 case []float32: 64 return SearchFloat32s(a, x.(float32)) 65 case []float64: 66 return SearchFloat64s(a, x.(float64)) 67 68 case []string: 69 return SearchStrings(a, x.(string)) 70 case [][]byte: 71 return SearchByteSlices(a, x.([]byte)) 72 case [][]rune: 73 return SearchRuneSlices(a, x.([]rune)) 74 } 75 76 panic("sort.Search passed an unknown type") 77 }