util: Rename SortedStrSliceCompare and move to util package

This commit is contained in:
Jonathan Gold
2018-03-28 17:41:32 -04:00
parent 7d7eb3d1cd
commit 3c8d424a43
5 changed files with 70 additions and 68 deletions

View File

@@ -19,6 +19,7 @@
package util
import (
"fmt"
"path"
"sort"
"strings"
@@ -376,3 +377,27 @@ func SystemBusPrivateUsable() (conn *dbus.Conn, err error) {
}
return conn, nil // success
}
// SortedStrSliceCompare takes two lists of strings and returns whether or not
// they are equivalent. It will return nil if both sets contain the same
// elements, regardless of order, and an error if they do not.
func SortedStrSliceCompare(a, b []string) error {
if len(a) != len(b) {
return fmt.Errorf("slices have different lengths: %d vs %d", len(a), len(b))
}
// make a copy of each to sort, so we don't reorder the inputs
x := make([]string, len(a))
y := make([]string, len(b))
copy(x, a)
copy(y, b)
sort.Strings(x)
sort.Strings(y)
for i := range x {
if x[i] != y[i] {
return fmt.Errorf("values do not match: %s vs %s", x[i], y[i])
}
}
return nil
}

View File

@@ -813,3 +813,45 @@ func TestUtilFlattenListWithSplit1(t *testing.T) {
}
}
}
func TestSortedStrSliceCompare0(t *testing.T) {
slice0 := []string{"foo", "bar", "baz"}
slice1 := []string{"bar", "foo", "baz"}
if err := SortedStrSliceCompare(slice0, slice1); err != nil {
t.Errorf("slices were not evaluated as equivalent: %v, %v", slice0, slice1)
}
}
func TestSortedStrSliceCompare1(t *testing.T) {
slice0 := []string{"foo", "bar", "baz"}
slice1 := []string{"fi", "fi", "fo"}
if err := SortedStrSliceCompare(slice0, slice1); err == nil {
t.Errorf("slices were evaluated as equivalent: %v, %v", slice0, slice1)
}
}
func TestSortedStrSliceCompare2(t *testing.T) {
slice0 := []string{"foo", "bar", "baz"}
slice1 := []string{"foo", "bar"}
if err := SortedStrSliceCompare(slice0, slice1); err == nil {
t.Errorf("slices were evaluated as equivalent: %v, %v", slice0, slice1)
}
}
func TestSortedStrSliceCompare3(t *testing.T) {
slice0 := []string{"foo", "bar", "baz"}
slice1 := []string{"zip", "zap", "zop"}
_ = SortedStrSliceCompare(slice0, slice1)
if slice0[0] != "foo" || slice0[1] != "bar" || slice0[2] != "baz" {
t.Errorf("input slice reordered to: %v", slice0)
}
if slice1[0] != "zip" || slice1[1] != "zap" || slice1[2] != "zop" {
t.Errorf("input slice reordered to: %v", slice1)
}
}