From 7e79ca02251d0e085e2f1fc05b3811291e85fc0b Mon Sep 17 00:00:00 2001 From: Chris Kuiper Date: Tue, 20 Aug 2019 23:27:29 -0700 Subject: Add tcpip.Route.String and tcpip.AddressMask.Prefix PiperOrigin-RevId: 264544163 --- pkg/tcpip/tcpip.go | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) (limited to 'pkg/tcpip') diff --git a/pkg/tcpip/tcpip.go b/pkg/tcpip/tcpip.go index 29a6025d9..3600a1349 100644 --- a/pkg/tcpip/tcpip.go +++ b/pkg/tcpip/tcpip.go @@ -31,6 +31,7 @@ package tcpip import ( "errors" "fmt" + "math/bits" "reflect" "strconv" "strings" @@ -145,8 +146,17 @@ type Address string type AddressMask string // String implements Stringer. -func (a AddressMask) String() string { - return Address(a).String() +func (m AddressMask) String() string { + return Address(m).String() +} + +// Prefix returns the number of bits before the first host bit. +func (m AddressMask) Prefix() int { + p := 0 + for _, b := range []byte(m) { + p += bits.LeadingZeros8(^b) + } + return p } // Subnet is a subnet defined by its address and mask. @@ -209,14 +219,7 @@ func (s *Subnet) Bits() (ones int, zeros int) { // Prefix returns the number of bits before the first host bit. func (s *Subnet) Prefix() int { - for i, b := range []byte(s.mask) { - for j := 7; j >= 0; j-- { - if b&(1< 0 { + fmt.Fprintf(&out, " via %s", r.Gateway) + } + fmt.Fprintf(&out, " nic %d", r.NIC) + return out.String() +} + // Match determines if r is viable for the given destination address. func (r *Route) Match(addr Address) bool { if len(addr) != len(r.Destination) { -- cgit v1.2.3