| 1 |
package num |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"runtime" |
| 6 |
"strconv" |
| 7 |
"strings" |
| 8 |
) |
| 9 |
|
| 10 |
// CPU parses the string s to see if it contains NumCPU()* (with the star), if so the number behind |
| 11 |
// it (without a space) multiplied with runtime.CPU() and returns, otherwise a number if assumed and that |
| 12 |
// is parsed. A negative number returns an error if seen after `numcpu()*`, but we allow -1 in the normal |
| 13 |
// expression. |
| 14 |
func CPU(s string) (int, error) { |
| 15 |
const numcpu = "numcpu()*" |
| 16 |
if strings.HasPrefix(strings.ToLower(s), numcpu) { |
| 17 |
n, err := strconv.Atoi(s[len(numcpu):]) |
| 18 |
if err != nil || n < 0 { |
| 19 |
return 0, fmt.Errorf("not a (positive) number after %s: %s", numcpu, s) |
| 20 |
} |
| 21 |
return runtime.NumCPU() * n, nil |
| 22 |
} |
| 23 |
|
| 24 |
n, err := strconv.Atoi(s) |
| 25 |
if err != nil || n < -1 { |
| 26 |
return 0, fmt.Errorf("not a number or less than -1: %s", s) |
| 27 |
} |
| 28 |
return n, nil |
| 29 |
|
| 30 |
} |