Skip to content

Commit

Permalink
use cmp.Compare, and test ForkSortFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
jchappelow committed Jun 7, 2024
1 parent c9a74c5 commit 2d7d24f
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
2 changes: 1 addition & 1 deletion common/chain/forks/forks.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func (f Fork) String() string {
// ForkSortFunc is used with slices.SortFunc or slices.SortStableFunc to sort a
// []*Fork in ascending order by height.
func ForkSortFunc(a, b *Fork) int {
return int(a.Height) - int(b.Height)
return cmp.Compare(a.Height, b.Height) // int(a.Height) - int(b.Height)
}

// matchForks is the primary helper method for returning for names and
Expand Down
67 changes: 67 additions & 0 deletions common/chain/forks/forks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,70 @@ func TestForks_sort(t *testing.T) {
slices.SortStableFunc(activeForks, forks.ForkSortFunc)
assert.Equal(t, activeForks, wantSorted)
}

func TestForkSortFunc(t *testing.T) {
tests := []struct {
name string
forks []*forks.Fork
expected []*forks.Fork
}{
{
name: "empty",
forks: []*forks.Fork{},
expected: []*forks.Fork{},
},
{
name: "single",
forks: []*forks.Fork{{Name: "a", Height: 1}},
expected: []*forks.Fork{{Name: "a", Height: 1}},
},
{
name: "sorted",
forks: []*forks.Fork{
{Name: "a", Height: 1},
{Name: "b", Height: 2},
{Name: "c", Height: 3},
},
expected: []*forks.Fork{
{Name: "a", Height: 1},
{Name: "b", Height: 2},
{Name: "c", Height: 3},
},
},
{
name: "unsorted",
forks: []*forks.Fork{
{Name: "c", Height: 3},
{Name: "a", Height: 1},
{Name: "b", Height: 2},
},
expected: []*forks.Fork{
{Name: "a", Height: 1},
{Name: "b", Height: 2},
{Name: "c", Height: 3},
},
},
{
name: "duplicate heights",
forks: []*forks.Fork{
{Name: "a", Height: 1},
{Name: "b", Height: 2},
{Name: "c", Height: 2},
{Name: "d", Height: 3},
},
expected: []*forks.Fork{
{Name: "a", Height: 1},
{Name: "b", Height: 2},
{Name: "c", Height: 2},
{Name: "d", Height: 3},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
slices.SortStableFunc(tt.forks, forks.ForkSortFunc)
assert.Equal(t, tt.expected, tt.forks)
})
}
}

0 comments on commit 2d7d24f

Please sign in to comment.