Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions numcpus_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,20 @@ func readCPURangeWith[T any](file string, f func(cpus string) (T, error)) (T, er
if err != nil {
return zero, err
}
return f(strings.Trim(string(buf), "\n "))
return f(string(buf))
}

func countCPURange(cpus string) (int, error) {
cpus = strings.Trim(cpus, "\n ")

// Treat empty file as valid. This might be the case if there are no offline CPUs in which
// case /sys/devices/system/cpu/offline is empty.
if cpus == "" {
return 0, nil
}

n := int(0)
for _, cpuRange := range strings.Split(cpus, ",") {
for cpuRange := range strings.SplitSeq(cpus, ",") {
if cpuRange == "" {
return 0, fmt.Errorf("empty CPU range in CPU string %q", cpus)
}
Expand All @@ -84,13 +86,15 @@ func countCPURange(cpus string) (int, error) {
}

func listCPURange(cpus string) ([]int, error) {
cpus = strings.Trim(cpus, "\n ")

// See comment in countCPURange.
if cpus == "" {
return []int{}, nil
}

list := []int{}
for _, cpuRange := range strings.Split(cpus, ",") {
for cpuRange := range strings.SplitSeq(cpus, ",") {
if cpuRange == "" {
return nil, fmt.Errorf("empty CPU range in CPU string %q", cpus)
}
Expand Down
14 changes: 14 additions & 0 deletions numcpus_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ func TestCPURange(t *testing.T) {
wantCount: 0,
wantList: []int{},
},
{
str: "\n",
wantCount: 0,
wantList: []int{},
},
{
str: "0",
wantCount: 1,
Expand Down Expand Up @@ -86,6 +91,11 @@ func TestCPURange(t *testing.T) {
wantCount: 9,
wantList: []int{0, 2, 3, 4, 6, 8, 9, 10, 31},
},
{
str: " 0,2-7\n",
wantCount: 7,
wantList: []int{0, 2, 3, 4, 5, 6, 7},
},
{
str: "invalid",
wantErr: true,
Expand Down Expand Up @@ -130,6 +140,10 @@ func TestCPURange(t *testing.T) {
str: "0,5-3",
wantErr: true,
},
{
str: "0, 5 - 3",
wantErr: true,
},
}

for _, tc := range testCases {
Expand Down