mirror of
https://github.com/libp2p/go-libp2p-peerstore.git
synced 2025-03-22 12:50:07 +08:00
reduce complexity in update addr book method
This commit is contained in:
parent
2ff9006762
commit
8c02e08cd3
@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
pstore "github.com/libp2p/go-libp2p-core/peerstore"
|
||||
"github.com/libp2p/go-libp2p-core/record"
|
||||
pb "github.com/libp2p/go-libp2p-peerstore/pb"
|
||||
"github.com/libp2p/go-libp2p-peerstore/pstoremem"
|
||||
|
||||
@ -467,36 +468,40 @@ func (ab *dsAddrBook) setAddrs(p peer.ID, addrs []ma.Multiaddr, ttl time.Duratio
|
||||
// }
|
||||
|
||||
newExp := time.Now().Add(ttl).Unix()
|
||||
// TODO this is very inefficient O(m*n); we could build a map to use as an
|
||||
// index, and test against it. That would turn it into O(m+n). This code
|
||||
// will be refactored entirely anyway, and it's not being used by users
|
||||
// (that we know of); so OK to keep it for now.
|
||||
updateExisting := func(entryList []*pb.AddrBookRecord_AddrEntry, incoming ma.Multiaddr) *pb.AddrBookRecord_AddrEntry {
|
||||
for _, have := range entryList {
|
||||
if incoming.Equal(have.Addr) {
|
||||
switch mode {
|
||||
case ttlOverride:
|
||||
have.Ttl = int64(ttl)
|
||||
have.Expiry = newExp
|
||||
case ttlExtend:
|
||||
if int64(ttl) > have.Ttl {
|
||||
have.Ttl = int64(ttl)
|
||||
}
|
||||
if newExp > have.Expiry {
|
||||
have.Expiry = newExp
|
||||
}
|
||||
default:
|
||||
panic("BUG: unimplemented ttl mode")
|
||||
}
|
||||
return have
|
||||
}
|
||||
var addrsMap map[string]*pb.AddrBookRecord_AddrEntry
|
||||
if len(addrs) > 0 {
|
||||
addrsMap = make(map[string]*pb.AddrBookRecord_AddrEntry, len(pr.Addrs))
|
||||
for _, addr := range pr.Addrs {
|
||||
addrsMap[addr.Addr.String()] = addr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
updateExisting := func(incoming ma.Multiaddr) *pb.AddrBookRecord_AddrEntry {
|
||||
existingEntry := addrsMap[incoming.String()]
|
||||
if existingEntry == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case ttlOverride:
|
||||
existingEntry.Ttl = int64(ttl)
|
||||
existingEntry.Expiry = newExp
|
||||
case ttlExtend:
|
||||
if int64(ttl) > existingEntry.Ttl {
|
||||
existingEntry.Ttl = int64(ttl)
|
||||
}
|
||||
if newExp > existingEntry.Expiry {
|
||||
existingEntry.Expiry = newExp
|
||||
}
|
||||
default:
|
||||
panic("BUG: unimplemented ttl mode")
|
||||
}
|
||||
return existingEntry
|
||||
}
|
||||
|
||||
var entries []*pb.AddrBookRecord_AddrEntry
|
||||
for _, incoming := range addrs {
|
||||
existingEntry := updateExisting(pr.Addrs, incoming)
|
||||
existingEntry := updateExisting(incoming)
|
||||
|
||||
if existingEntry == nil {
|
||||
// if signed {
|
||||
|
Loading…
Reference in New Issue
Block a user