intmap.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2017 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package flags
  14. import (
  15. "fmt"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. )
  20. // IntMap is a map[string]int64 container for command line flags. The default
  21. // initialization will create an empty map. If you need default backing map use
  22. // NewIntMap.
  23. type IntMap map[string]int64
  24. func (m *IntMap) String() string {
  25. s := make([]string, 0, len(*m))
  26. for k, v := range *m {
  27. s = append(s, fmt.Sprintf("%s=%d", k, v))
  28. }
  29. sort.Strings(s)
  30. return strings.Join(s, ",")
  31. }
  32. // Get returns the values of m. The interface will need to be type asserted to
  33. // IntMap for use.
  34. func (m *IntMap) Get() interface{} {
  35. return *m
  36. }
  37. // Set will take a string in the format <key1>=<value1>,<key2>=<value2> and
  38. // parse the resulting value into a map[string]int64. Values may contain "=",
  39. // keys may not.
  40. func (m *IntMap) Set(v string) error {
  41. *m = IntMap{}
  42. for _, entry := range strings.Split(v, ",") {
  43. data := strings.SplitN(entry, "=", 2)
  44. if len(data) != 2 {
  45. return fmt.Errorf("invalid key=value pair: %s", entry)
  46. }
  47. k := strings.TrimSpace(data[0])
  48. vString := strings.TrimSpace(data[1])
  49. if len(k) == 0 {
  50. return fmt.Errorf("invalid key=value pair: %s", entry)
  51. }
  52. var err error
  53. v := 0
  54. if len(vString) != 0 {
  55. v, err = strconv.Atoi(vString)
  56. if err != nil {
  57. return err
  58. }
  59. }
  60. (*m)[k] = int64(v)
  61. }
  62. return nil
  63. }
  64. // NewIntMap will wrap the pointer to the map in a IntMap and set the
  65. // underlying map to val.
  66. func NewIntMap(p *map[string]int64, val map[string]int64) *IntMap {
  67. *p = val
  68. return (*IntMap)(p)
  69. }