Skip to content

Commit

Permalink
Convenience functions for converting to/from standard library types
Browse files Browse the repository at this point in the history
  • Loading branch information
ipfreely-uk committed Jan 12, 2025
1 parent 609e369 commit 64b0558
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 0 deletions.
23 changes: 23 additions & 0 deletions ipstd/net.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package ipstd

import (
"net"

"github.com/ipfreely-uk/go/ip"
)

func ToIP(a ip.Address) net.IP {
return a.Bytes()
}

func FromIP(a net.IP) ip.Address {
return ip.MustFromBytes(a...)
}

func ToIPMask(a ip.Address) net.IPMask {
return a.Bytes()
}

func FromIPMask(a net.IPMask) ip.Address {
return ip.MustFromBytes(a...)
}
23 changes: 23 additions & 0 deletions ipstd/net_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package ipstd_test

import (
"testing"

"github.com/ipfreely-uk/go/ip"
"github.com/ipfreely-uk/go/ipstd"
"github.com/stretchr/testify/assert"
)

func TestToIP(t *testing.T) {
expected := ip.MustParse(ip.V4(), "127.0.0.1")
n := ipstd.ToIP(expected)
actual := ipstd.FromIP(n)
assert.Equal(t, expected, actual, n.String())
}

func TestToIPMask(t *testing.T) {
expected := ip.MustParse(ip.V4(), "127.0.0.1")
n := ipstd.ToIPMask(expected)
actual := ipstd.FromIPMask(n)
assert.Equal(t, expected, actual, n.String())
}
16 changes: 16 additions & 0 deletions ipstd/netip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ipstd

import (
"net/netip"

"github.com/ipfreely-uk/go/ip"
)

func ToAddr(a ip.Address) netip.Addr {
r, _ := netip.AddrFromSlice(a.Bytes())
return r
}

func FromAddr(a netip.Addr) ip.Address {
return ip.MustFromBytes(a.AsSlice()...)
}
16 changes: 16 additions & 0 deletions ipstd/netip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ipstd_test

import (
"testing"

"github.com/ipfreely-uk/go/ip"
"github.com/ipfreely-uk/go/ipstd"
"github.com/stretchr/testify/assert"
)

func TestToAddr(t *testing.T) {
expected := ip.MustParse(ip.V4(), "127.0.0.1")
n := ipstd.ToAddr(expected)
actual := ipstd.FromAddr(n)
assert.Equal(t, expected, actual)
}
4 changes: 4 additions & 0 deletions ipstd/package.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/*
Convenience functions to convert to & from standard library types.
*/
package ipstd

0 comments on commit 64b0558

Please sign in to comment.