Przeglądaj źródła

Add support for sorting keys that are arrays.

Anaminus 10 lat temu
rodzic
commit
a4b53deb9b
2 zmienionych plików z 34 dodań i 11 usunięć
  1. 29 11
      spew/common.go
  2. 5 0
      spew/common_test.go

+ 29 - 11
spew/common.go

@@ -340,24 +340,42 @@ func (s *valuesSorter) Swap(i, j int) {
 	s.values[i], s.values[j] = s.values[j], s.values[i]
 }
 
-// Less returns whether the value at index i should sort before the
-// value at index j.  It is part of the sort.Interface implementation.
-func (s *valuesSorter) Less(i, j int) bool {
-	switch s.values[i].Kind() {
+// valueSortLess returns whether the first value should sort before the second
+// value.  It is used by valueSorter.Less as part of the sort.Interface
+// implementation.
+func valueSortLess(a, b reflect.Value) bool {
+	switch a.Kind() {
 	case reflect.Bool:
-		return !s.values[i].Bool() && s.values[j].Bool()
+		return !a.Bool() && b.Bool()
 	case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
-		return s.values[i].Int() < s.values[j].Int()
+		return a.Int() < b.Int()
 	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
-		return s.values[i].Uint() < s.values[j].Uint()
+		return a.Uint() < b.Uint()
 	case reflect.Float32, reflect.Float64:
-		return s.values[i].Float() < s.values[j].Float()
+		return a.Float() < b.Float()
 	case reflect.String:
-		return s.values[i].String() < s.values[j].String()
+		return a.String() < b.String()
 	case reflect.Uintptr:
-		return s.values[i].Uint() < s.values[j].Uint()
+		return a.Uint() < b.Uint()
+	case reflect.Array:
+		// Compare the contents of both arrays.
+		l := a.Len()
+		for i := 0; i < l; i++ {
+			av := a.Index(i)
+			bv := b.Index(i)
+			if av.Interface() == bv.Interface() {
+				continue
+			}
+			return valueSortLess(av, bv)
+		}
 	}
-	return s.values[i].String() < s.values[j].String()
+	return a.String() < b.String()
+}
+
+// Less returns whether the value at index i should sort before the
+// value at index j.  It is part of the sort.Interface implementation.
+func (s *valuesSorter) Less(i, j int) bool {
+	return valueSortLess(s.values[i], s.values[j])
 }
 
 // sortValues is a generic sort function for native types: int, uint, bool,

+ 5 - 0
spew/common_test.go

@@ -166,6 +166,11 @@ func TestSortValues(t *testing.T) {
 			[]reflect.Value{b, a, c},
 			[]reflect.Value{a, b, c},
 		},
+		// Array
+		{
+			[]reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})},
+			[]reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})},
+		},
 		// Uintptrs.
 		{
 			[]reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))},