p2p: use slices package for sorting #27494 (#1705)

This commit is contained in:
Daniel Liu 2025-12-07 18:14:25 +08:00 committed by GitHub
parent 8be96e4622
commit 35c905a131
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 12 additions and 18 deletions

View file

@ -22,7 +22,7 @@ package discover
import (
"fmt"
"net"
"sort"
"slices"
"time"
"github.com/XinFinOrg/XDPoSChain/log"
@ -33,14 +33,6 @@ const (
ntpChecks = 3 // Number of measurements to do against the NTP server
)
// durationSlice attaches the methods of sort.Interface to []time.Duration,
// sorting in increasing order.
type durationSlice []time.Duration
func (s durationSlice) Len() int { return len(s) }
func (s durationSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s durationSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// checkClockDrift queries an NTP server for clock drifts and warns the user if
// one large enough is detected.
func checkClockDrift() {
@ -109,7 +101,7 @@ func sntpDrift(measurements int) (time.Duration, error) {
drifts = append(drifts, sent.Sub(t)+elapsed/2)
}
// Calculate average drif (drop two extremities to avoid outliers)
sort.Sort(durationSlice(drifts))
slices.Sort(drifts)
drift := time.Duration(0)
for i := 1; i < len(drifts)-1; i++ {

View file

@ -21,7 +21,7 @@ import (
"fmt"
"io"
"net"
"sort"
"slices"
"sync"
"time"
@ -325,7 +325,7 @@ func countMatchingProtocols(protocols []Protocol, caps []Cap) int {
// matchProtocols creates structures for matching named subprotocols.
func matchProtocols(protocols []Protocol, caps []Cap, rw MsgReadWriter) map[string]*protoRW {
sort.Sort(capsByNameAndVersion(caps))
slices.SortFunc(caps, Cap.Cmp)
offset := baseProtocolLength
result := make(map[string]*protoRW)

View file

@ -17,7 +17,9 @@
package p2p
import (
"cmp"
"fmt"
"strings"
"github.com/XinFinOrg/XDPoSChain/p2p/discover"
)
@ -72,10 +74,10 @@ func (cap Cap) String() string {
return fmt.Sprintf("%s/%d", cap.Name, cap.Version)
}
type capsByNameAndVersion []Cap
func (cs capsByNameAndVersion) Len() int { return len(cs) }
func (cs capsByNameAndVersion) Swap(i, j int) { cs[i], cs[j] = cs[j], cs[i] }
func (cs capsByNameAndVersion) Less(i, j int) bool {
return cs[i].Name < cs[j].Name || (cs[i].Name == cs[j].Name && cs[i].Version < cs[j].Version)
// Cmp defines the canonical sorting order of capabilities.
func (cap Cap) Cmp(other Cap) int {
if cap.Name == other.Name {
return cmp.Compare(cap.Version, other.Version)
}
return strings.Compare(cap.Name, other.Name)
}