From dcacdad4746429cc92c12a33eaf22f879408e47a Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Wed, 18 May 2022 15:26:56 -0700 Subject: [PATCH] unix: use ByteSliceFromString in (*Ifreq).Name CL 340370 introduced (*Ifreq).Name method which scans the Ifrn field for \0 twice -- first explicitly, when by calling BytePtrToString. It seems more straightforward to use ByteSliceToString instead. The differences are: - simpler code; - no double scanning for \0; - in case there is no \0 in the Ifrn (unlikely), the full string (rather than an empty string) is now returned. With the last item in mind, the test case with no \0 as input that expects empty output fails, so drop it. Alternatively, we could test that it returns the full string, but it will be essentially testing ByteSliceToString, which is not the point. Cc: Matt Layher Change-Id: I31d4f6dbe98aae5120f9b2246c93ceaa6a165395 Reviewed-on: https://go-review.googlesource.com/c/sys/+/407194 Reviewed-by: Ian Lance Taylor Auto-Submit: Ian Lance Taylor Reviewed-by: Matt Layher TryBot-Result: Gopher Robot Run-TryBot: Matt Layher Reviewed-by: Dmitri Shuralyov Run-TryBot: Ian Lance Taylor --- unix/ifreq_linux.go | 9 +-------- unix/ifreq_linux_test.go | 11 ----------- 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/unix/ifreq_linux.go b/unix/ifreq_linux.go index 934af313..15721a51 100644 --- a/unix/ifreq_linux.go +++ b/unix/ifreq_linux.go @@ -8,7 +8,6 @@ package unix import ( - "bytes" "unsafe" ) @@ -45,13 +44,7 @@ func NewIfreq(name string) (*Ifreq, error) { // Name returns the interface name associated with the Ifreq. func (ifr *Ifreq) Name() string { - // BytePtrToString requires a NULL terminator or the program may crash. If - // one is not present, just return the empty string. - if !bytes.Contains(ifr.raw.Ifrn[:], []byte{0x00}) { - return "" - } - - return BytePtrToString(&ifr.raw.Ifrn[0]) + return ByteSliceToString(ifr.raw.Ifrn[:]) } // According to netdevice(7), only AF_INET addresses are returned for numerous diff --git a/unix/ifreq_linux_test.go b/unix/ifreq_linux_test.go index 7a6d56cf..b81a8b63 100644 --- a/unix/ifreq_linux_test.go +++ b/unix/ifreq_linux_test.go @@ -39,17 +39,6 @@ func TestIfreqSize(t *testing.T) { } func TestIfreqName(t *testing.T) { - // Invalid ifreq (no NULL terminator), so expect empty string. - var name [IFNAMSIZ]byte - for i := range name { - name[i] = 0xff - } - - bad := &Ifreq{raw: ifreq{Ifrn: name}} - if got := bad.Name(); got != "" { - t.Fatalf("expected empty ifreq name, but got: %q", got) - } - // Valid ifreq, expect the hard-coded testIfreq name. ifr := testIfreq(t) if want, got := ifreqName, ifr.Name(); want != got {