From d349a3231e8ff9da108e5bb01486cc4c909aa068 Mon Sep 17 00:00:00 2001 From: julianknodt Date: Tue, 13 Jul 2021 10:12:47 -0700 Subject: [PATCH] wgcfg: use string cut instead of string split Signed-off-by: julianknodt --- wgengine/wgcfg/parser.go | 16 +++++++++++----- wgengine/wgcfg/parser_test.go | 3 ++- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/wgengine/wgcfg/parser.go b/wgengine/wgcfg/parser.go index f1637ac14..6f70ed00f 100644 --- a/wgengine/wgcfg/parser.go +++ b/wgengine/wgcfg/parser.go @@ -69,6 +69,14 @@ func parseKeyHex(s string) (*wgkey.Key, error) { return &key, nil } +// stringsCut is strings.Cut from proposed https://github.com/golang/go/issues/46336. +func stringsCut(s, sep string) (before, after string, found bool) { + if i := strings.Index(s, sep); i >= 0 { + return s[:i], s[i+len(sep):], true + } + return s, "", false +} + // FromUAPI generates a Config from r. // r should be generated by calling device.IpcGetOperation; // it is not compatible with other uapi streams. @@ -83,12 +91,10 @@ func FromUAPI(r io.Reader) (*Config, error) { if line == "" { continue } - parts := strings.Split(line, "=") - if len(parts) != 2 { - return nil, fmt.Errorf("failed to parse line %q, found %d =-separated parts, want 2", line, len(parts)) + key, value, ok := stringsCut(line, "=") + if !ok { + return nil, fmt.Errorf("failed to cut line %q on =", line) } - key := parts[0] - value := parts[1] valueBytes := scanner.Bytes()[len(key)+1:] if key == "public_key" { diff --git a/wgengine/wgcfg/parser_test.go b/wgengine/wgcfg/parser_test.go index 46b3bea72..35f4919b0 100644 --- a/wgengine/wgcfg/parser_test.go +++ b/wgengine/wgcfg/parser_test.go @@ -7,6 +7,7 @@ import ( "bufio" "bytes" + "io" "reflect" "runtime" "testing" @@ -90,10 +91,10 @@ func BenchmarkFromUAPI(b *testing.B) { r := bytes.NewReader(buf.Bytes()) b.ReportAllocs() for i := 0; i < b.N; i++ { + r.Seek(0, io.SeekStart) _, err := FromUAPI(r) if err != nil { b.Errorf("failed from UAPI: %v", err) } - r.Seek(0, 0) } }