simplify sort.Sort by using sort.Slice (#17066)

This commit is contained in:
Harshavardhana
2023-04-24 13:28:18 -07:00
committed by GitHub
parent 6addc7a35d
commit 8fd07bcd51
7 changed files with 39 additions and 78 deletions

View File

@@ -111,25 +111,6 @@ func getHostIP(host string) (ipList set.StringSet, err error) {
return ipList, err
}
// byLastOctetValue implements sort.Interface used in sorting a list
// of ip address by their last octet value in descending order.
type byLastOctetValue []net.IP
func (n byLastOctetValue) Len() int { return len(n) }
func (n byLastOctetValue) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n byLastOctetValue) Less(i, j int) bool {
// This case is needed when all ips in the list
// have same last octets, Following just ensures that
// 127.0.0.1 is moved to the end of the list.
if n[i].IsLoopback() {
return false
}
if n[j].IsLoopback() {
return true
}
return []byte(n[i].To4())[3] > []byte(n[j].To4())[3]
}
// sortIPs - sort ips based on higher octects.
// The logic to sort by last octet is implemented to
// prefer CIDRs with higher octects, this in-turn skips the
@@ -152,7 +133,18 @@ func sortIPs(ipList []string) []string {
}
}
sort.Sort(byLastOctetValue(ipV4s))
sort.Slice(ipV4s, func(i, j int) bool {
// This case is needed when all ips in the list
// have same last octets, Following just ensures that
// 127.0.0.1 is moved to the end of the list.
if ipV4s[i].IsLoopback() {
return false
}
if ipV4s[j].IsLoopback() {
return true
}
return []byte(ipV4s[i].To4())[3] > []byte(ipV4s[j].To4())[3]
})
var ips []string
for _, ip := range ipV4s {