github.com/puellanivis/breton@v0.2.16/lib/sort/float.template (about) 1 package sort 2 3 import ( 4 "math" 5 "sort" 6 ) 7 8 // {{.Name}}Slice attaches the methods of sort.Interface to []{{.Type}}, sorting in increasing order. 9 type {{.Name}}Slice []{{.Type}} 10 11 // Len implements sort.Interface. 12 func (p {{.Name}}Slice) Len() int { return len(p) } 13 14 // Less implements sort.Interface. 15 func (p {{.Name}}Slice) Less(i, j int) bool { return p[i] < p[j] || isNaN{{.Width}}(p[i]) && !isNaN{{.Width}}(p[j]) } 16 17 // Swap implements sort.Interface. 18 func (p {{.Name}}Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } 19 20 func cmp{{.Name}}(x, y {{.Type}}) int { 21 if x == y { 22 return 0 23 } 24 25 if x < y { 26 return -1 27 } 28 29 return +1 30 } 31 32 // Compare implements Comparer. 33 func (p {{.Name}}Slice) Compare(i, j int) int { 34 return cmp{{.Name}}(p[i], p[j]) 35 } 36 37 // CompareFunc implements Comparer. 38 func (p {{.Name}}Slice) CompareFunc(x interface{}) func(int) int { 39 e := x.({{.Type}}) 40 return func(i int) int { 41 return cmp{{.Name}}(p[i], e) 42 } 43 } 44 45 // RadixRange implements RadixInterface. 46 func (p {{.Name}}Slice) RadixRange() (int, int) { 47 return 0, {{.MSB}} 48 } 49 50 // RadixFunc implements RadixInterface. 51 func (p {{.Name}}Slice) RadixFunc(r int) RadixTest { 52 if r == 0 { 53 return func(i int) bool { 54 return p[i] >= 0 55 } 56 } 57 58 mask := uint{{.Width}}(1) << uint({{.MSB}}-r) 59 sign := uint{{.Width}}(1) << {{.MSB}} 60 return func(i int) bool { 61 bits := math.Float{{.Width}}bits(p[i]) 62 return (bits&mask != 0) != (bits&sign != 0) 63 } 64 } 65 66 // Sort is a convenience method. 67 func (p {{.Name}}Slice) Sort() { radix(p) } 68 69 // Radix is a convenience method. 70 func (p {{.Name}}Slice) Radix() { radix(p) } 71 72 // Search is a convenience method. 73 func (p {{.Name}}Slice) Search(x {{.Type}}) int { return Search{{.Name}}s(p, x) } 74 75 // SearchFor is a convenience method. 76 func (p {{.Name}}Slice) SearchFor(x interface{}) int { return Search{{.Name}}s(p, x.({{.Type}})) } 77 78 // {{.Name}}s sorts a slice of {{.Type}}s in increasing order. 79 func {{.Name}}s(a []{{.Type}}) { radix({{.Name}}Slice(a)) } 80 81 // Search{{.Name}}s searches for x in a sorted slice of {{.Type}}s and returns the index as specified by sort.Search. 82 // The return value is the index to insert x if x is not present (it could be len(a)). 83 // The slice must be sorted in ascending order. 84 func Search{{.Name}}s(a []{{.Type}}, x {{.Type}}) int { 85 return sort.Search(len(a), func(i int) bool { return a[i] >= x }) 86 } 87 88 // {{.Name}}sAreSorted tests whether a slice of {{.Type}}s is sorted in increasing order. 89 func {{.Name}}sAreSorted(a []{{.Type}}) bool { return sort.IsSorted({{.Name}}Slice(a)) }