parsers.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Package parsers provides helper functions to parse and validate different type
  2. // of string. It can be hosts, unix addresses, tcp addresses, filters, kernel
  3. // operating system versions.
  4. package parsers
  5. import (
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. )
  10. // ParseKeyValueOpt parses and validates the specified string as a key/value pair (key=value)
  11. func ParseKeyValueOpt(opt string) (string, string, error) {
  12. parts := strings.SplitN(opt, "=", 2)
  13. if len(parts) != 2 {
  14. return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt)
  15. }
  16. return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil
  17. }
  18. // ParseUintList parses and validates the specified string as the value
  19. // found in some cgroup file (e.g. `cpuset.cpus`, `cpuset.mems`), which could be
  20. // one of the formats below. Note that duplicates are actually allowed in the
  21. // input string. It returns a `map[int]bool` with available elements from `val`
  22. // set to `true`.
  23. // Supported formats:
  24. // 7
  25. // 1-6
  26. // 0,3-4,7,8-10
  27. // 0-0,0,1-7
  28. // 03,1-3 <- this is gonna get parsed as [1,2,3]
  29. // 3,2,1
  30. // 0-2,3,1
  31. func ParseUintList(val string) (map[int]bool, error) {
  32. if val == "" {
  33. return map[int]bool{}, nil
  34. }
  35. availableInts := make(map[int]bool)
  36. split := strings.Split(val, ",")
  37. errInvalidFormat := fmt.Errorf("invalid format: %s", val)
  38. for _, r := range split {
  39. if !strings.Contains(r, "-") {
  40. v, err := strconv.Atoi(r)
  41. if err != nil {
  42. return nil, errInvalidFormat
  43. }
  44. availableInts[v] = true
  45. } else {
  46. split := strings.SplitN(r, "-", 2)
  47. min, err := strconv.Atoi(split[0])
  48. if err != nil {
  49. return nil, errInvalidFormat
  50. }
  51. max, err := strconv.Atoi(split[1])
  52. if err != nil {
  53. return nil, errInvalidFormat
  54. }
  55. if max < min {
  56. return nil, errInvalidFormat
  57. }
  58. for i := min; i <= max; i++ {
  59. availableInts[i] = true
  60. }
  61. }
  62. }
  63. return availableInts, nil
  64. }