diff --git a/p2p/discover/ntp.go b/p2p/discover/ntp.go index 67d2204f125d..c120ef842cc3 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 6cabe89342ef..bf7cf1add0f1 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -21,7 +21,7 @@ import ( "fmt" "io" "net" - "sort" + "slices" "sync" "time" @@ -329,7 +329,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 deb86f985c34..f924028cce31 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) }