From 4271ecf73fc3a7777c4898e8609554670f3e43c2 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Tue, 22 Oct 2024 22:58:00 -0700 Subject: [PATCH] libct/cg/fs: refactor getCpusetStat Using strings.Cut (added in Go 1.18, see [1]) results in faster and cleaner code with less allocations (as we're not using a slice). This also drops the check for extra dash (we're unlikely to get it from the kernel anyway). While at it, rename min/max -> from/to to avoid collision with Go min/max builtins. This code is tested by TestCPUSetStats* tests. [1]: https://github.com/golang/go/issues/46336 Signed-off-by: Kir Kolyshkin --- libcontainer/cgroups/fs/cpuset.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/libcontainer/cgroups/fs/cpuset.go b/libcontainer/cgroups/fs/cpuset.go index 4cf1f30ff..b51413ba8 100644 --- a/libcontainer/cgroups/fs/cpuset.go +++ b/libcontainer/cgroups/fs/cpuset.go @@ -48,26 +48,23 @@ func getCpusetStat(path string, file string) ([]uint16, error) { } for _, s := range strings.Split(fileContent, ",") { - sp := strings.SplitN(s, "-", 3) - switch len(sp) { - case 3: - return extracted, &parseError{Path: path, File: file, Err: errors.New("extra dash")} - case 2: - min, err := strconv.ParseUint(sp[0], 10, 16) + fromStr, toStr, ok := strings.Cut(s, "-") + if ok { + from, err := strconv.ParseUint(fromStr, 10, 16) if err != nil { return extracted, &parseError{Path: path, File: file, Err: err} } - max, err := strconv.ParseUint(sp[1], 10, 16) + to, err := strconv.ParseUint(toStr, 10, 16) if err != nil { return extracted, &parseError{Path: path, File: file, Err: err} } - if min > max { - return extracted, &parseError{Path: path, File: file, Err: errors.New("invalid values, min > max")} + if from > to { + return extracted, &parseError{Path: path, File: file, Err: errors.New("invalid values, from > to")} } - for i := min; i <= max; i++ { + for i := from; i <= to; i++ { extracted = append(extracted, uint16(i)) } - case 1: + } else { value, err := strconv.ParseUint(s, 10, 16) if err != nil { return extracted, &parseError{Path: path, File: file, Err: err}