diff --git a/common/common.go b/common/common.go index 45d05c21695..2534bc47ef4 100644 --- a/common/common.go +++ b/common/common.go @@ -15,6 +15,7 @@ import ( "path/filepath" "reflect" "regexp" + "slices" "strconv" "strings" "sync" @@ -666,3 +667,12 @@ func Batch[S ~[]E, E any](blobs S, batchSize int) (batches []S) { } return } + +// Sort takes a slice of fmt.Stringer implementers and returns a new sorted slice +func Sort[S ~[]E, E fmt.Stringer](x S) S { + n := slices.Clone(x) + slices.SortFunc(n, func(a, b E) int { + return strings.Compare(a.String(), b.String()) + }) + return n +} diff --git a/common/common_test.go b/common/common_test.go index 6f2df157715..736b5c9e775 100644 --- a/common/common_test.go +++ b/common/common_test.go @@ -866,3 +866,14 @@ func TestBatch(t *testing.T) { require.Len(t, b[1], 3) require.Len(t, b[2], 1) } + +type A int + +func (a A) String() string { + return strconv.Itoa(int(a)) +} + +// TestSort exercises Sort +func TestSort(t *testing.T) { + assert.Equal(t, Sort([]A{6, 2, 5, 1}), []A{1, 2, 5, 6}) +}