From 35c905a1312c2f1779d8fcf264fa6b3e750e615e Mon Sep 17 00:00:00 2001 From: Daniel Liu <139250065@qq.com> Date: Sun, 7 Dec 2025 18:14:25 +0800 Subject: [PATCH] p2p: use slices package for sorting #27494 (#1705) --- p2p/discover/ntp.go | 12 ++---------- p2p/peer.go | 4 ++-- p2p/protocol.go | 14 ++++++++------ 3 files changed, 12 insertions(+), 18 deletions(-) diff --git a/p2p/discover/ntp.go b/p2p/discover/ntp.go index 67d2204f12..c120ef842c 100644 --- a/p2p/discover/ntp.go +++ b/p2p/discover/ntp.go @@ -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++ { diff --git a/p2p/peer.go b/p2p/peer.go index 4119bac3dd..b5cbc86617 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -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) diff --git a/p2p/protocol.go b/p2p/protocol.go index deb86f985c..f924028cce 100644 --- a/p2p/protocol.go +++ b/p2p/protocol.go @@ -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) }