Skip to content

Commit

Permalink
Use a strings.Builder in Peer.String with explicit nil fields
Browse files Browse the repository at this point in the history
Signed-off-by: Yolan Romailler <anomalroil@users.noreply.github.com>
  • Loading branch information
AnomalRoil committed Apr 22, 2024
1 parent 001f394 commit cfa61fb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
20 changes: 12 additions & 8 deletions peer/peer.go
Expand Up @@ -24,6 +24,7 @@ import (
"context"
"fmt"
"net"
"strings"

"google.golang.org/grpc/credentials"
)
Expand All @@ -46,18 +47,21 @@ func (p *Peer) String() string {
if p == nil {
return "Peer<nil>"
}
ret := "Peer{"
sb := &strings.Builder{}
sb.WriteString("Peer{")
if p.Addr != nil {
ret += fmt.Sprintf("Addr: '%s'", p.Addr.String())
fmt.Fprintf(sb, "Addr: '%s', ", p.Addr.String())
} else {
fmt.Fprintf(sb, "Addr: <nil>, ")
}
if p.AuthInfo != nil {
if len(ret) > 5 {
ret += ", "
}
ret += fmt.Sprintf("AuthInfo: '%s'", p.AuthInfo.AuthType())
fmt.Fprintf(sb, "AuthInfo: '%s'", p.AuthInfo.AuthType())
} else {
fmt.Fprintf(sb, "AuthInfo: <nil>")
}
ret += "}"
return ret
sb.WriteString("}")

return sb.String()
}

type peerKey struct{}
Expand Down
6 changes: 3 additions & 3 deletions peer/peer_test.go
Expand Up @@ -103,15 +103,15 @@ func TestPeerStringer(t *testing.T) {
{
addr: &addr{"1.2.3.4:1234"},
authLevel: -1,
want: "Peer{Addr: '1.2.3.4:1234'}",
want: "Peer{Addr: '1.2.3.4:1234', AuthInfo: <nil>}",
},
{
authLevel: credentials.InvalidSecurityLevel,
want: "Peer{AuthInfo: 'testAuthInfo'}",
want: "Peer{Addr: <nil>, AuthInfo: 'testAuthInfo'}",
},
{
authLevel: -1,
want: "Peer{}",
want: "Peer{Addr: <nil>, AuthInfo: <nil>}",
},
}
for _, tc := range testCases {
Expand Down

0 comments on commit cfa61fb

Please sign in to comment.