replace strings.Split(N) for strings.Cut() or alternatives

Go 1.18 and up now provides a strings.Cut() which is better suited for
splitting key/value pairs (and similar constructs), and performs better:

```go
func BenchmarkSplit(b *testing.B) {
        b.ReportAllocs()
        data := []string{"12hello=world", "12hello=", "12=hello", "12hello"}
        for i := 0; i < b.N; i++ {
                for _, s := range data {
                        _ = strings.SplitN(s, "=", 2)[0]
                }
        }
}

func BenchmarkCut(b *testing.B) {
        b.ReportAllocs()
        data := []string{"12hello=world", "12hello=", "12=hello", "12hello"}
        for i := 0; i < b.N; i++ {
                for _, s := range data {
                        _, _, _ = strings.Cut(s, "=")
                }
        }
}
```

    BenchmarkSplit
    BenchmarkSplit-10            8244206               128.0 ns/op           128 B/op          4 allocs/op
    BenchmarkCut
    BenchmarkCut-10             54411998                21.80 ns/op            0 B/op          0 allocs/op

While looking at occurrences of `strings.Split()`, I also updated some for alternatives,
or added some constraints; for cases where an specific number of items is expected, I used `strings.SplitN()`
with a suitable limit. This prevents (theoretical) unlimited splits.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn
2022-11-04 09:05:39 +01:00
parent f90219d472
commit eaedadbed0
19 changed files with 96 additions and 106 deletions

View File

@@ -100,9 +100,7 @@ type data struct {
func cleanProfileName(profile string) string {
// Normally profiles are suffixed by " (enforce)". AppArmor profiles cannot
// contain spaces so this doesn't restrict daemon profile names.
if parts := strings.SplitN(profile, " ", 2); len(parts) >= 1 {
profile = parts[0]
}
profile, _, _ = strings.Cut(profile, " ")
if profile == "" {
profile = "unconfined"
}
@@ -184,17 +182,18 @@ func parseVersion(output string) (int, error) {
// Copyright (C) 1999-2008 Novell Inc.
// Copyright 2009-2012 Canonical Ltd.
lines := strings.SplitN(output, "\n", 2)
words := strings.Split(lines[0], " ")
version := words[len(words)-1]
version, _, _ := strings.Cut(output, "\n")
if i := strings.LastIndex(version, " "); i >= 0 {
version = version[i+1:]
}
// trim "-beta1" suffix from version="3.0.0-beta1" if exists
version = strings.SplitN(version, "-", 2)[0]
version, _, _ = strings.Cut(version, "-")
// also trim tilde
version = strings.SplitN(version, "~", 2)[0]
version, _, _ = strings.Cut(version, "~")
// split by major minor version
v := strings.Split(version, ".")
v := strings.SplitN(version, ".", 4)
if len(v) == 0 || len(v) > 3 {
return -1, fmt.Errorf("parsing version failed for output: `%s`", output)
}