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