Skip to content

Commit

Permalink
Merge pull request #9 from libp2p/fix/nil-is-not-nil
Browse files Browse the repository at this point in the history
avoid the nil is not nil footgun
  • Loading branch information
vyzo authored Feb 3, 2022
2 parents e03ee6f + 475599e commit 4f7a0ba
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
24 changes: 24 additions & 0 deletions p2p/host/resource-manager/rcmgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
}
15 changes: 15 additions & 0 deletions p2p/host/resource-manager/rcmgr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 4f7a0ba

Please sign in to comment.