Skip to content

Commit

Permalink
pkg/ipnet: Teach IPNet.String() to handle nil receivers
Browse files Browse the repository at this point in the history
Instead of panicking.  This makes some comparisons easier, as you can
see from the test changes.
  • Loading branch information
wking committed Sep 19, 2018
1 parent 5f59fec commit 36d5eb0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
9 changes: 9 additions & 0 deletions pkg/ipnet/ipnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ type IPNet struct {
net.IPNet
}

// String returns a CIDR serialization of the subnet, or an empty
// string if the subnet is nil.
func (ipnet *IPNet) String() string {
if ipnet == nil {
return ""
}
return ipnet.IPNet.String()
}

// MarshalJSON interface for an IPNet
func (ipnet IPNet) MarshalJSON() (data []byte, err error) {
if reflect.DeepEqual(ipnet.IPNet, emptyIPNet) {
Expand Down
18 changes: 7 additions & 11 deletions pkg/ipnet/ipnet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,19 @@ func TestUnmarshal(t *testing.T) {
Mask: net.IPv4Mask(255, 255, 255, 0),
}},
} {
data, err := json.Marshal(ipNetIn)
if err != nil {
t.Fatal(err)
}
t.Run(ipNetIn.String(), func(t *testing.T) {
data, err := json.Marshal(ipNetIn)
if err != nil {
t.Fatal(err)
}

t.Run(string(data), func(t *testing.T) {
var ipNetOut *IPNet
err := json.Unmarshal(data, &ipNetOut)
err = json.Unmarshal(data, &ipNetOut)
if err != nil {
t.Fatal(err)
}

if ipNetIn == nil {
if ipNetOut != nil {
t.Fatalf("%v != %v", ipNetOut, ipNetIn)
}
} else if ipNetOut.String() != ipNetIn.String() {
if ipNetOut.String() != ipNetIn.String() {
t.Fatalf("%v != %v", ipNetOut, ipNetIn)
}
})
Expand Down

0 comments on commit 36d5eb0

Please sign in to comment.