Skip to content

Commit d3a80c7

Browse files
zx2c4bradfitz
authored andcommitted
net/netip: add Addr.AsSlice() method
We have AddrFrom4, AddrFrom6, AddrFromSlice and As4, As6, but we are missing AsSlice, so this commit adds the missing function. It also gets rid of the less ergonomic and inconsistently named IPAddrParts. Updates #49298. Change-Id: I1c6a2c32fc6c69b244ab49765412ffe3bbe7e5c2 Reviewed-on: https://go-review.googlesource.com/c/go/+/360874 Trust: Jason A. Donenfeld <[email protected]> Trust: Josh Bleecher Snyder <[email protected]> Run-TryBot: Jason A. Donenfeld <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 35a5881 commit d3a80c7

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed

src/net/netip/netip.go

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -448,31 +448,6 @@ func (ip Addr) Less(ip2 Addr) bool { return ip.Compare(ip2) == -1 }
448448

449449
func (ip Addr) lessOrEq(ip2 Addr) bool { return ip.Compare(ip2) <= 0 }
450450

451-
// ipZone returns the standard library net.IP from ip, as well
452-
// as the zone.
453-
// The optional reuse IP provides memory to reuse.
454-
func (ip Addr) ipZone(reuse []byte) (stdIP []byte, zone string) {
455-
base := reuse[:0]
456-
switch {
457-
case ip.z == z0:
458-
return nil, ""
459-
case ip.Is4():
460-
a4 := ip.As4()
461-
return append(base, a4[:]...), ""
462-
default:
463-
a16 := ip.As16()
464-
return append(base, a16[:]...), ip.Zone()
465-
}
466-
}
467-
468-
// IPAddrParts returns the net.IPAddr representation of an Addr.
469-
//
470-
// The slice will be nil if ip is the zero Addr.
471-
// The zone is the empty string if there is no zone.
472-
func (ip Addr) IPAddrParts() (slice []byte, zone string) {
473-
return ip.ipZone(nil)
474-
}
475-
476451
// Is4 reports whether ip is an IPv4 address.
477452
//
478453
// It returns false for IP4-mapped IPv6 addresses. See IP.Unmap.
@@ -718,6 +693,23 @@ func (ip Addr) As4() (a4 [4]byte) {
718693
panic("As4 called on IPv6 address")
719694
}
720695

696+
// AsSlice returns an IPv4 or IPv6 address in its respective 4-byte or 16-byte representation.
697+
func (ip Addr) AsSlice() []byte {
698+
switch ip.z {
699+
case z0:
700+
return nil
701+
case z4:
702+
var ret [4]byte
703+
bePutUint32(ret[:], uint32(ip.addr.lo))
704+
return ret[:]
705+
default:
706+
var ret [16]byte
707+
bePutUint64(ret[:8], ip.addr.hi)
708+
bePutUint64(ret[8:], ip.addr.lo)
709+
return ret[:]
710+
}
711+
}
712+
721713
// Next returns the address following ip.
722714
// If there is none, it returns the zero Addr.
723715
func (ip Addr) Next() Addr {

0 commit comments

Comments
 (0)