Skip to content

Commit d83d533

Browse files
committed
libct/cg/fscommon: GetValueByKey: use strings.CutPrefix
Using strings.CutPrefix (added in Go 1.20, see [1]) results in faster and cleaner code with less allocations (as the code only allocates memory for the value, and does it once). While at it, improve the function documentation. [1]: golang/go#42537 Signed-off-by: Kir Kolyshkin <[email protected]>
1 parent f134871 commit d83d533

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

libcontainer/cgroups/fscommon/utils.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,20 +72,21 @@ func ParseKeyValue(t string) (string, uint64, error) {
7272
return key, value, nil
7373
}
7474

75-
// GetValueByKey reads a key-value pairs from the specified cgroup file,
76-
// and returns a value of the specified key. ParseUint is used for value
77-
// conversion.
75+
// GetValueByKey reads space-separated "key value" pairs from the specified
76+
// cgroup file, looking for a specified key, and returns its value as uint64,
77+
// using [ParseUint] for conversion. If the value is not found, 0 is returned.
7878
func GetValueByKey(path, file, key string) (uint64, error) {
7979
content, err := cgroups.ReadFile(path, file)
8080
if err != nil {
8181
return 0, err
8282
}
8383

84+
key += " "
8485
lines := strings.Split(content, "\n")
8586
for _, line := range lines {
86-
arr := strings.Split(line, " ")
87-
if len(arr) == 2 && arr[0] == key {
88-
val, err := ParseUint(arr[1], 10, 64)
87+
v, ok := strings.CutPrefix(line, key)
88+
if ok {
89+
val, err := ParseUint(v, 10, 64)
8990
if err != nil {
9091
err = &ParseError{Path: path, File: file, Err: err}
9192
}

0 commit comments

Comments
 (0)