Skip to content

Commit

Permalink
feat: add helper function to handle cim IP Addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
d-strobel committed Dec 29, 2024
1 parent 6d716cf commit 54da90d
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 0 deletions.
35 changes: 35 additions & 0 deletions parsing/cim_ip_address.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package parsing

import (
"encoding/json"
"fmt"
"net/netip"
)

// CimIpAddress represents an IP Address value.
type CimIpAddress netip.Addr

// UnmarshalJSON implements the json.Unmarshaler interface for the CimIpAddress type.
func (a *CimIpAddress) UnmarshalJSON(b []byte) error {
// Parse the integer from the JSON input
var addr uint32
if err := json.Unmarshal(b, &addr); err != nil {
return fmt.Errorf("parsing.UnmarshalJSON(CimIpAddress): failed to parse IP address from JSON: %w", err)
}

// Convert integer to IPv4 address
ip := [4]byte{
byte(addr),
byte(addr >> 8),
byte(addr >> 16),
byte(addr >> 24),
}

// Use netip to create the address
parsedAddr := netip.AddrFrom4(ip)

// Assign the parsed address to the pointer receiver
*a = CimIpAddress(parsedAddr)

return nil
}
59 changes: 59 additions & 0 deletions parsing/cim_ip_address_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package parsing

import (
"encoding/json"
"net/netip"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestCimIpAddressUnmarshalJSON(t *testing.T) {
t.Parallel()

t.Run("ValidIPv4Address", func(t *testing.T) {
// Valid integer representation of 10.100.91.51
jsonData := `861627402`
var ip CimIpAddress

err := json.Unmarshal([]byte(jsonData), &ip)
require.NoError(t, err)

expectedIP := netip.MustParseAddr("10.100.91.51")
assert.Equal(t, expectedIP, netip.Addr(ip))
})

t.Run("InvalidJSONFormat", func(t *testing.T) {
// Invalid JSON (string instead of integer)
jsonData := `"notAnInteger"`
var ip CimIpAddress

err := json.Unmarshal([]byte(jsonData), &ip)
assert.Error(t, err)
})

t.Run("ZeroAddress", func(t *testing.T) {
// Test edge case with 0
jsonData := `0`
var ip CimIpAddress

err := json.Unmarshal([]byte(jsonData), &ip)
require.NoError(t, err)

expectedIP := netip.MustParseAddr("0.0.0.0")
assert.Equal(t, expectedIP, netip.Addr(ip))
})

t.Run("MaxIPv4Address", func(t *testing.T) {
// Test edge case with maximum IPv4 address (255.255.255.255)
jsonData := `4294967295` // Equivalent to 255.255.255.255
var ip CimIpAddress

err := json.Unmarshal([]byte(jsonData), &ip)
require.NoError(t, err)

expectedIP := netip.MustParseAddr("255.255.255.255")
assert.Equal(t, expectedIP, netip.Addr(ip))
})
}

0 comments on commit 54da90d

Please sign in to comment.