Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test to ensure that database packing produces sorted values #1560

Merged
merged 4 commits into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions database/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package database

import (
"math/rand"
"testing"

"github.com/stretchr/testify/require"

"golang.org/x/exp/slices"

"github.com/ava-labs/avalanchego/utils"
)

func TestSortednessUint64(t *testing.T) {
StephenButtolph marked this conversation as resolved.
Show resolved Hide resolved
ints := make([]uint64, 1024)
for i := range ints {
ints[i] = rand.Uint64() //#nosec G404
}
slices.Sort(ints)

intBytes := make([][]byte, 1024)
for i, val := range ints {
intBytes[i] = PackUInt64(val)
}
require.True(t, utils.IsSortedBytes(intBytes))
}

func TestSortednessUint32(t *testing.T) {
ints := make([]uint32, 1024)
for i := range ints {
ints[i] = rand.Uint32() //#nosec G404
}
slices.Sort(ints)

intBytes := make([][]byte, 1024)
for i, val := range ints {
intBytes[i] = PackUInt32(val)
}
require.True(t, utils.IsSortedBytes(intBytes))
}
10 changes: 10 additions & 0 deletions utils/sorting.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@ func SortBytes[T ~[]byte](arr []T) {
})
}

// Returns true iff the elements in [arr] are sorted.
func IsSortedBytes[T ~[]byte](arr []T) bool {
StephenButtolph marked this conversation as resolved.
Show resolved Hide resolved
for i := 0; i < len(arr)-1; i++ {
if bytes.Compare(arr[i], arr[i+1]) == 1 {
return false
}
}
return true
}

// Returns true iff the elements in [s] are unique and sorted.
func IsSortedAndUniqueSortable[T Sortable[T]](s []T) bool {
for i := 0; i < len(s)-1; i++ {
Expand Down