From 9de339f9c6bc54d6f2462be0940dfc71c2c01a4c Mon Sep 17 00:00:00 2001 From: itchyny Date: Tue, 29 Oct 2024 08:56:20 +0900 Subject: [PATCH] refactor color parsing and environ loader using strings.Cut --- cli/color.go | 19 ++++--------------- cli/error.go | 8 +++----- compiler.go | 4 ++-- 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/cli/color.go b/cli/color.go index 21a02759..2b418439 100644 --- a/cli/color.go +++ b/cli/color.go @@ -41,32 +41,21 @@ func validColor(x string) bool { return false } } - return num || x == "" + return num } func setColors(colors string) error { - var i int var color string for _, target := range []*[]byte{ &nullColor, &falseColor, &trueColor, &numberColor, &stringColor, &objectKeyColor, &arrayColor, &objectColor, } { - if i < len(colors) { - if j := strings.IndexByte(colors[i:], ':'); j >= 0 { - color = colors[i : i+j] - i += j + 1 - } else { - color = colors[i:] - i = len(colors) - } + color, colors, _ = strings.Cut(colors, ":") + if color != "" { if !validColor(color) { return fmt.Errorf("invalid color: %q", color) } - if color == "" { - *target = nil - } else { - *target = newColor(color) - } + *target = newColor(color) } else { *target = nil } diff --git a/cli/error.go b/cli/error.go index 17c26c4a..bb6d4aa0 100644 --- a/cli/error.go +++ b/cli/error.go @@ -125,13 +125,11 @@ func (err *yamlParseError) Error() string { msg := strings.TrimPrefix( strings.TrimPrefix(err.err.Error(), "yaml: "), "unmarshal errors:\n ") - if fmt.Sscanf(msg, "line %d: ", &line); line == 0 { + if _, e := fmt.Sscanf(msg, "line %d: ", &line); e != nil { return "invalid yaml: " + err.fname } - msg = msg[strings.Index(msg, ": ")+2:] - if i := strings.IndexByte(msg, '\n'); i >= 0 { - msg = msg[:i] - } + _, msg, _ = strings.Cut(msg, ": ") + msg, _, _ = strings.Cut(msg, "\n") linestr := getLineByLine(err.contents, line) return fmt.Sprintf("invalid yaml: %s:%d\n%s %s", err.fname, line, formatLineInfo(linestr, line, 0), msg) diff --git a/compiler.go b/compiler.go index d328779a..3fcb83f2 100644 --- a/compiler.go +++ b/compiler.go @@ -913,8 +913,8 @@ func (c *compiler) compileFunc(e *Func) error { env := make(map[string]any) if c.environLoader != nil { for _, kv := range c.environLoader() { - if i := strings.IndexByte(kv, '='); i > 0 { - env[kv[:i]] = kv[i+1:] + if k, v, ok := strings.Cut(kv, "="); ok && k != "" { + env[k] = v } } }