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

Use slices package for most sorting #27474

Closed
Closed
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
f1b2b48
trie; use slices.SortFunc instead of sort.Sort
Jun 14, 2023
9aa1958
trie; use slices.SortFunc instead of sort.Sort
Jun 14, 2023
c81918c
stacktrie; use slices.SortFunc instead of sort.Sort
Jun 14, 2023
6992248
rangeproof; use slices.SortFunc instead of sort.Sort
Jun 14, 2023
0e112ed
tests; use slices.Sort instead of sort.Sort
Jun 14, 2023
7f11a8c
apitypes; use slices.Sort instead of sort.Sort
Jun 14, 2023
e3e3605
tests; use slices.Sort instead of sort.Sort
Jun 14, 2023
39a44d4
main; use slices.Sort instead of sort.Strings
Jun 14, 2023
dd12c97
main, console, vm, fetcher, dbtest, memorydb, jsre, les, prometheus, …
Jun 14, 2023
2fc0108
msgrate; use slices method instead of sort method for sorting
Jun 14, 2023
7b38713
dnsdisc; use slices method instead of sort method for sorting
Jun 14, 2023
97d2de6
discover; use slices method instead of sort method for sorting
Jun 14, 2023
1b96e1c
discover; use slices method instead of sort method for sorting
Jun 14, 2023
cf1cb36
discover; use slices method instead of sort method for sorting
Jun 14, 2023
49f8dd5
discover; use slices method instead of sort method for sorting
Jun 14, 2023
9a75f71
discover; use slices method instead of sort method for sorting
Jun 14, 2023
6860c9f
p2p; use slices method instead of sort method for sorting
Jun 14, 2023
767c7b7
metrics; use slices method instead of sort method for sorting
Jun 14, 2023
340d73e
metrics; use slices method instead of sort method for sorting
Jun 14, 2023
2ca34c0
metrics; use slices method instead of sort method for sorting
Jun 14, 2023
08498ee
utils; use slices method instead of sort method for sorting
Jun 14, 2023
ea340cb
les; use slices method instead of sort method for sorting
Jun 14, 2023
92513a5
ethapi; use slices method instead of sort method for sorting
Jun 14, 2023
d49f65b
tracers; use slices method instead of sort method for sorting
Jun 14, 2023
b388208
dbtest; use slices method instead of sort method for sorting
Jun 14, 2023
9a79c5a
snap, gasprice; use slices method instead of sort method for sorting
Jun 14, 2023
4220502
eth, gasprice; use slices method instead of sort method for sorting
Jun 14, 2023
d167778
txpool; use slices method instead of sort method for sorting
Jun 14, 2023
bdd8e7e
build, devp2p, clique, forkid, core; use slices method instead of sor…
Jun 14, 2023
dde34cd
devp2p, core; use slices method instead of sort method for sorting
Jun 14, 2023
224b66f
trie; revert sorting changes
Jun 14, 2023
7bbc72a
trie; revert sorting changes
Jun 14, 2023
03b94ee
utils; remove dropListItem.Less
Jun 14, 2023
d1384ff
snap; revert changes
Jun 14, 2023
890aa4a
gasprice,trie; use slices method instead of sort method for sorting
Jun 14, 2023
818e751
snap; use slices method instead of sort method for sorting
Jun 14, 2023
5d92f12
keystore, snapshot; use slices method instead of sort method for sorting
Jun 14, 2023
fcd9dbb
p2p; implement capLessFunc to replace Cap.Less
Jun 14, 2023
3dcea2f
keystore; fix typo
Jun 14, 2023
3510e8e
metrics; use namedMetricsLessFunc instead of Less function
Jun 14, 2023
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
11 changes: 5 additions & 6 deletions accounts/keystore/account_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,17 @@ import (
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
"golang.org/x/exp/slices"
)

// Minimum amount of time between cache reloads. This limit applies if the platform does
// not support change notifications. It also applies if the keystore directory does not
// exist yet, the code will attempt to create a watcher at most this often.
const minReloadInterval = 2 * time.Second

type accountsByURL []accounts.Account

func (s accountsByURL) Len() int { return len(s) }
func (s accountsByURL) Less(i, j int) bool { return s[i].URL.Cmp(s[j].URL) < 0 }
func (s accountsByURL) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func accountsByURLLess(a, b accounts.Account) bool {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't want to add a Less function on accounts.Account so did this instead

return a.URL.Cmp(b.URL) < 0
}

// AmbiguousAddrError is returned when attempting to unlock
// an address for which more than one file exists.
Expand Down Expand Up @@ -194,7 +193,7 @@ func (ac *accountCache) find(a accounts.Account) (accounts.Account, error) {
default:
err := &AmbiguousAddrError{Addr: a.Address, Matches: make([]accounts.Account, len(matches))}
copy(err.Matches, matches)
sort.Sort(accountsByURL(err.Matches))
slices.SortFunc(err.Matches, accountsByURLLess)
return accounts.Account{}, err
}
}
Expand Down
4 changes: 2 additions & 2 deletions accounts/keystore/account_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ import (
"os"
"path/filepath"
"reflect"
"sort"
"testing"
"time"

"github.com/cespare/cp"
"github.com/davecgh/go-spew/spew"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -203,7 +203,7 @@ func TestCacheAddDeleteOrder(t *testing.T) {
// Check that the account list is sorted by filename.
wantAccounts := make([]accounts.Account, len(accs))
copy(wantAccounts, accs)
sort.Sort(accountsByURL(wantAccounts))
slices.SortFunc(wantAccounts, accountsByURLLess)
list := cache.accounts()
if !reflect.DeepEqual(list, wantAccounts) {
t.Fatalf("got accounts: %s\nwant %s", spew.Sdump(accs), spew.Sdump(wantAccounts))
Expand Down
4 changes: 2 additions & 2 deletions accounts/keystore/keystore_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"math/rand"
"os"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
Expand All @@ -31,6 +30,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/event"
"golang.org/x/exp/slices"
)

var testSigData = make([]byte, 32)
Expand Down Expand Up @@ -424,7 +424,7 @@ func checkAccounts(t *testing.T, live map[common.Address]accounts.Account, walle
for _, account := range live {
liveList = append(liveList, account)
}
sort.Sort(accountsByURL(liveList))
slices.SortFunc(liveList, accountsByURLLess)
for j, wallet := range wallets {
if accs := wallet.Accounts(); len(accs) != 1 {
t.Errorf("wallet %d: contains invalid number of accounts: have %d, want 1", j, len(accs))
Expand Down
12 changes: 3 additions & 9 deletions build/update-license.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,13 @@ import (
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"

"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -152,13 +153,6 @@ func (i info) gpl() bool {
return false
}

// authors implements the sort.Interface for strings in case-insensitive mode.
type authors []string

func (as authors) Len() int { return len(as) }
func (as authors) Less(i, j int) bool { return strings.ToLower(as[i]) < strings.ToLower(as[j]) }
func (as authors) Swap(i, j int) { as[i], as[j] = as[j], as[i] }

func main() {
var (
files = getFiles()
Expand Down Expand Up @@ -299,7 +293,7 @@ func writeAuthors(files []string) {
}
}
// Write sorted list of authors back to the file.
sort.Sort(authors(list))
slices.Sort(list)
content := new(bytes.Buffer)
content.WriteString(authorsFileHeader)
for _, a := range list {
Expand Down
10 changes: 5 additions & 5 deletions cmd/devp2p/dns_route53.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"context"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
Expand All @@ -33,6 +32,7 @@ import (
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/dnsdisc"
"github.com/urfave/cli/v2"
"golang.org/x/exp/slices"
)

const (
Expand Down Expand Up @@ -288,11 +288,11 @@ func makeDeletionChanges(records map[string]recordSet, keep map[string]string) [
// sortChanges ensures DNS changes are in leaf-added -> root-changed -> leaf-deleted order.
func sortChanges(changes []types.Change) {
score := map[string]int{"CREATE": 1, "UPSERT": 2, "DELETE": 3}
sort.Slice(changes, func(i, j int) bool {
if changes[i].Action == changes[j].Action {
return *changes[i].ResourceRecordSet.Name < *changes[j].ResourceRecordSet.Name
slices.SortFunc(changes, func(a, b types.Change) bool {
if a.Action == b.Action {
return *a.ResourceRecordSet.Name < *b.ResourceRecordSet.Name
}
return score[string(changes[i].Action)] < score[string(changes[j].Action)]
return score[string(a.Action)] < score[string(b.Action)]
})
}

Expand Down
10 changes: 5 additions & 5 deletions cmd/devp2p/nodeset.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ import (
"encoding/json"
"fmt"
"os"
"sort"
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/p2p/enode"
"golang.org/x/exp/slices"
)

const jsonIndent = " "
Expand Down Expand Up @@ -77,8 +77,8 @@ func (ns nodeSet) nodes() []*enode.Node {
result = append(result, n.N)
}
// Sort by ID.
sort.Slice(result, func(i, j int) bool {
return bytes.Compare(result[i].ID().Bytes(), result[j].ID().Bytes()) < 0
slices.SortFunc(result, func(a, b *enode.Node) bool {
return bytes.Compare(a.ID().Bytes(), b.ID().Bytes()) < 0
})
return result
}
Expand All @@ -103,8 +103,8 @@ func (ns nodeSet) topN(n int) nodeSet {
for _, v := range ns {
byscore = append(byscore, v)
}
sort.Slice(byscore, func(i, j int) bool {
return byscore[i].Score >= byscore[j].Score
slices.SortFunc(byscore, func(a, b nodeJSON) bool {
return a.Score >= b.Score
})
result := make(nodeSet, n)
for _, v := range byscore[:n] {
Expand Down
4 changes: 2 additions & 2 deletions cmd/devp2p/nodesetcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"errors"
"fmt"
"net"
"sort"
"strconv"
"strings"
"time"
Expand All @@ -30,6 +29,7 @@ import (
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/urfave/cli/v2"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -89,7 +89,7 @@ func showAttributeCounts(ns nodeSet) {
maxlength = len(key)
}
}
sort.Strings(keys)
slices.Sort(keys)
fmt.Println("ENR attribute counts:")
for _, key := range keys {
fmt.Printf("%s%s: %d\n", strings.Repeat(" ", maxlength-len(key)+1), key, attrcount[key])
Expand Down
13 changes: 4 additions & 9 deletions consensus/clique/snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package clique
import (
"bytes"
"encoding/json"
"sort"
"time"

"github.com/ethereum/go-ethereum/common"
Expand All @@ -29,6 +28,7 @@ import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"golang.org/x/exp/slices"
)

// Vote represents a single vote that an authorized signer made to modify the
Expand Down Expand Up @@ -62,13 +62,6 @@ type Snapshot struct {
Tally map[common.Address]Tally `json:"tally"` // Current vote tally to avoid recalculating
}

// signersAscending implements the sort interface to allow sorting a list of addresses
type signersAscending []common.Address

func (s signersAscending) Len() int { return len(s) }
func (s signersAscending) Less(i, j int) bool { return bytes.Compare(s[i][:], s[j][:]) < 0 }
func (s signersAscending) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// newSnapshot creates a new snapshot with the specified startup parameters. This
// method does not initialize the set of recent signers, so only ever use if for
// the genesis block.
Expand Down Expand Up @@ -315,7 +308,9 @@ func (s *Snapshot) signers() []common.Address {
for sig := range s.Signers {
sigs = append(sigs, sig)
}
sort.Sort(signersAscending(sigs))
slices.SortFunc(sigs, func(a, b common.Address) bool {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could reasonably define a Less function on common.Address. I decided not to do so in this PR, but something to consider for the maintainers.

return bytes.Compare(a[:], b[:]) < 0
})
return sigs
}

Expand Down
6 changes: 4 additions & 2 deletions consensus/clique/snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"crypto/ecdsa"
"fmt"
"math/big"
"sort"
"testing"

"github.com/ethereum/go-ethereum/common"
Expand All @@ -31,6 +30,7 @@ import (
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
"golang.org/x/exp/slices"
)

// testerAccountPool is a pool to maintain currently active tester accounts,
Expand All @@ -53,7 +53,9 @@ func (ap *testerAccountPool) checkpoint(header *types.Header, signers []string)
for i, signer := range signers {
auths[i] = ap.address(signer)
}
sort.Sort(signersAscending(auths))
slices.SortFunc(auths, func(a, b common.Address) bool {
return bytes.Compare(a[:], b[:]) < 0
})
for i, auth := range auths {
copy(header.Extra[extraVanity+i*common.AddressLength:], auth.Bytes())
}
Expand Down
4 changes: 2 additions & 2 deletions console/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"os/signal"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"syscall"
Expand All @@ -38,6 +37,7 @@ import (
"github.com/ethereum/go-ethereum/rpc"
"github.com/mattn/go-colorable"
"github.com/peterh/liner"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -342,7 +342,7 @@ func (c *Console) Welcome() {
for api, version := range apis {
modules = append(modules, fmt.Sprintf("%s:%s", api, version))
}
sort.Strings(modules)
slices.Sort(modules)
message += " modules: " + strings.Join(modules, " ") + "\n"
}
message += "\nTo exit, press ctrl-d or type exit"
Expand Down
6 changes: 3 additions & 3 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"io"
"math/big"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
Expand All @@ -48,6 +47,7 @@ import (
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/trie"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -1015,8 +1015,8 @@ func (bc *BlockChain) procFutureBlocks() {
}
}
if len(blocks) > 0 {
sort.Slice(blocks, func(i, j int) bool {
return blocks[i].NumberU64() < blocks[j].NumberU64()
slices.SortFunc(blocks, func(a, b *types.Block) bool {
return a.NumberU64() < b.NumberU64()
})
// Insert one by one as chain insertion needs contiguous ancestry between blocks
for i := range blocks {
Expand Down
6 changes: 3 additions & 3 deletions core/forkid/forkid.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ import (
"math"
"math/big"
"reflect"
"sort"
"strings"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
"golang.org/x/exp/slices"
)

var (
Expand Down Expand Up @@ -270,8 +270,8 @@ func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) {
}
}
}
sort.Slice(forksByBlock, func(i, j int) bool { return forksByBlock[i] < forksByBlock[j] })
sort.Slice(forksByTime, func(i, j int) bool { return forksByTime[i] < forksByTime[j] })
slices.Sort(forksByBlock)
slices.Sort(forksByTime)

// Deduplicate fork identifiers applying multiple forks
for i := 1; i < len(forksByBlock); i++ {
Expand Down
14 changes: 5 additions & 9 deletions core/mkalloc.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,18 @@ import (

type allocItem struct{ Addr, Balance *big.Int }

type allocList []allocItem

func (a allocList) Len() int { return len(a) }
func (a allocList) Less(i, j int) bool { return a[i].Addr.Cmp(a[j].Addr) < 0 }
func (a allocList) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

func makelist(g *core.Genesis) allocList {
a := make(allocList, 0, len(g.Alloc))
func makelist(g *core.Genesis) []allocItem {
a := make([]allocItem, 0, len(g.Alloc))
for addr, account := range g.Alloc {
if len(account.Storage) > 0 || len(account.Code) > 0 || account.Nonce != 0 {
panic(fmt.Sprintf("can't encode account %x", addr))
}
bigAddr := new(big.Int).SetBytes(addr.Bytes())
a = append(a, allocItem{bigAddr, account.Balance})
}
sort.Sort(a)
slices.SortFunc(a, func(b, c allocItem) bool {
return b.Addr.Cmp(c.Addr) < 0
})
return a
}

Expand Down
Loading