2021-12-19 19:51:38 +08:00
|
|
|
package pstoremem
|
2016-04-20 06:18:24 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
|
2017-02-04 04:49:59 +08:00
|
|
|
ma "github.com/multiformats/go-multiaddr"
|
2019-10-29 06:32:22 +08:00
|
|
|
mafmt "github.com/multiformats/go-multiaddr-fmt"
|
2021-07-02 10:31:17 +08:00
|
|
|
manet "github.com/multiformats/go-multiaddr/net"
|
2016-04-20 06:18:24 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func isFDCostlyTransport(a ma.Multiaddr) bool {
|
|
|
|
return mafmt.TCP.Matches(a)
|
|
|
|
}
|
|
|
|
|
2021-12-19 19:51:38 +08:00
|
|
|
type addrList []ma.Multiaddr
|
2016-04-20 06:18:24 +08:00
|
|
|
|
2021-12-19 19:51:38 +08:00
|
|
|
func (al addrList) Len() int { return len(al) }
|
|
|
|
func (al addrList) Swap(i, j int) { al[i], al[j] = al[j], al[i] }
|
2016-04-20 06:18:24 +08:00
|
|
|
|
2021-12-19 19:51:38 +08:00
|
|
|
func (al addrList) Less(i, j int) bool {
|
2016-04-20 06:18:24 +08:00
|
|
|
a := al[i]
|
|
|
|
b := al[j]
|
|
|
|
|
|
|
|
// dial localhost addresses next, they should fail immediately
|
|
|
|
lba := manet.IsIPLoopback(a)
|
|
|
|
lbb := manet.IsIPLoopback(b)
|
2021-12-19 19:51:38 +08:00
|
|
|
if lba && !lbb {
|
|
|
|
return true
|
2016-04-20 06:18:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// dial utp and similar 'non-fd-consuming' addresses first
|
|
|
|
fda := isFDCostlyTransport(a)
|
|
|
|
fdb := isFDCostlyTransport(b)
|
|
|
|
if !fda {
|
2021-07-16 08:47:50 +08:00
|
|
|
return fdb
|
2016-04-20 06:18:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// if 'b' doesnt take a file descriptor
|
|
|
|
if !fdb {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// if 'b' is loopback and both take file descriptors
|
|
|
|
if lbb {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// for the rest, just sort by bytes
|
|
|
|
return bytes.Compare(a.Bytes(), b.Bytes()) > 0
|
|
|
|
}
|