mirror of
https://github.com/libp2p/go-libp2p-resource-manager.git
synced 2025-01-27 12:50:07 +08:00
avoid the nil is not nil footgun
This commit is contained in:
parent
fb6dc1ebda
commit
961bd2b66e
24
rcmgr.go
24
rcmgr.go
@ -474,6 +474,12 @@ func (s *peerScope) Peer() peer.ID {
|
||||
func (s *connectionScope) PeerScope() network.PeerScope {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// avoid nil is not nil footgun; go....
|
||||
if s.peer == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.peer
|
||||
}
|
||||
|
||||
@ -510,6 +516,12 @@ func (s *connectionScope) SetPeer(p peer.ID) error {
|
||||
func (s *streamScope) ProtocolScope() network.ProtocolScope {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// avoid nil is not nil footgun; go....
|
||||
if s.proto == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.proto
|
||||
}
|
||||
|
||||
@ -559,6 +571,12 @@ func (s *streamScope) SetProtocol(proto protocol.ID) error {
|
||||
func (s *streamScope) ServiceScope() network.ServiceScope {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// avoid nil is not nil footgun; go....
|
||||
if s.svc == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.svc
|
||||
}
|
||||
|
||||
@ -611,5 +629,11 @@ func (s *streamScope) SetService(svc string) error {
|
||||
func (s *streamScope) PeerScope() network.PeerScope {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
// avoid nil is not nil footgun; go....
|
||||
if s.peer == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return s.peer
|
||||
}
|
||||
|
@ -291,6 +291,11 @@ func TestResourceManager(t *testing.T) {
|
||||
checkResources(t, &s.rc, network.ScopeStat{NumConnsInbound: 1, NumFD: 1})
|
||||
})
|
||||
|
||||
// check nility of current peer scope
|
||||
if conn1.PeerScope() != nil {
|
||||
t.Fatal("peer scope should be nil")
|
||||
}
|
||||
|
||||
// attach to a peer
|
||||
if err := conn1.SetPeer(peerA); err != nil {
|
||||
t.Fatal(err)
|
||||
@ -435,6 +440,11 @@ func TestResourceManager(t *testing.T) {
|
||||
checkResources(t, &s.rc, network.ScopeStat{NumStreamsInbound: 1})
|
||||
})
|
||||
|
||||
// check nility of protocol scope
|
||||
if stream1.ProtocolScope() != nil {
|
||||
t.Fatal("protocol scope should be nil")
|
||||
}
|
||||
|
||||
if err := stream1.SetProtocol(protoA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@ -574,6 +584,11 @@ func TestResourceManager(t *testing.T) {
|
||||
checkResources(t, &s.rc, network.ScopeStat{})
|
||||
})
|
||||
|
||||
// check nility of current service scope
|
||||
if stream1.ServiceScope() != nil {
|
||||
t.Fatal("service scope should be nil")
|
||||
}
|
||||
|
||||
// we should be able to attach stream1 and stream2 to svcA, but stream3 should fail due to limit
|
||||
if err := stream1.SetService(svcA); err != nil {
|
||||
t.Fatal(err)
|
||||
|
Loading…
Reference in New Issue
Block a user