Skip to content

Commit c6d8b27

Browse files
committed
libct/cg/sd: stop using regex, fix systemdVersionAtoi
Rewrite systemdVersionAtoi to not use regexp, and fix two issues: 1. It was returning 0 (rather than -1) for some errors. 2. The comment was saying that the input string is without quotes, while in fact it is. Note the new function, similar to the old one, works on input either with or without quotes. Amend the test to add test cases without quotes. Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
1 parent 968ef53 commit c6d8b27

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

libcontainer/cgroups/systemd/common.go

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"fmt"
88
"math"
99
"os"
10-
"regexp"
1110
"strconv"
1211
"strings"
1312
"sync"
@@ -441,18 +440,21 @@ func systemdVersion(cm *dbusConnManager) int {
441440
return version
442441
}
443442

444-
func systemdVersionAtoi(verStr string) (int, error) {
445-
// verStr should be of the form:
446-
// "v245.4-1.fc32", "245", "v245-1.fc32", "245-1.fc32" (without quotes).
443+
func systemdVersionAtoi(str string) (int, error) {
444+
// str should be of the form:
445+
// "v245.4-1.fc32", "245", "v245-1.fc32", "245-1.fc32" (with quotes).
447446
// The result for all of the above should be 245.
448-
// Thus, we unconditionally remove the "v" prefix
447+
// Thus, we unconditionally remove the "v prefix
449448
// and then match on the first integer we can grab.
450-
re := regexp.MustCompile(`v?([0-9]+)`)
451-
matches := re.FindStringSubmatch(verStr)
452-
if len(matches) < 2 {
453-
return 0, fmt.Errorf("can't parse version %s: incorrect number of matches %v", verStr, matches)
449+
str = strings.TrimLeft(str, `"v`)
450+
for i := 0; i < len(str); i++ {
451+
if str[i] < '0' || str[i] > '9' {
452+
// First non-digit.
453+
str = str[:i]
454+
break
455+
}
454456
}
455-
ver, err := strconv.Atoi(matches[1])
457+
ver, err := strconv.Atoi(str)
456458
if err != nil {
457459
return -1, fmt.Errorf("can't parse version: %w", err)
458460
}

libcontainer/cgroups/systemd/systemd_test.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,11 @@ func TestSystemdVersion(t *testing.T) {
4040
{`"v245.4-1.fc32"`, 245, false},
4141
{`"241-1"`, 241, false},
4242
{`"v241-1"`, 241, false},
43-
{"NaN", 0, true},
44-
{"", 0, true},
43+
{`333.45"`, 333, false},
44+
{`v321-0`, 321, false},
45+
{"NaN", -1, true},
46+
{"", -1, true},
47+
{"v", -1, true},
4548
}
4649
for _, sdTest := range systemdVersionTests {
4750
ver, err := systemdVersionAtoi(sdTest.verStr)

0 commit comments

Comments
 (0)