本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.0KB

  1. // Copyright 2019 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package util
  14. import (
  15. "strconv"
  16. )
  17. // TODO(mdlayher): util packages are an anti-pattern and this should be moved
  18. // somewhere else that is more focused in the future.
  19. // A ValueParser enables parsing a single string into a variety of data types
  20. // in a concise and safe way. The Err method must be invoked after invoking
  21. // any other methods to ensure a value was successfully parsed.
  22. type ValueParser struct {
  23. v string
  24. err error
  25. }
  26. // NewValueParser creates a ValueParser using the input string.
  27. func NewValueParser(v string) *ValueParser {
  28. return &ValueParser{v: v}
  29. }
  30. // PInt64 interprets the underlying value as an int64 and returns a pointer to
  31. // that value.
  32. func (vp *ValueParser) PInt64() *int64 {
  33. if vp.err != nil {
  34. return nil
  35. }
  36. // A base value of zero makes ParseInt infer the correct base using the
  37. // string's prefix, if any.
  38. const base = 0
  39. v, err := strconv.ParseInt(vp.v, base, 64)
  40. if err != nil {
  41. vp.err = err
  42. return nil
  43. }
  44. return &v
  45. }
  46. // PUInt64 interprets the underlying value as an uint64 and returns a pointer to
  47. // that value.
  48. func (vp *ValueParser) PUInt64() *uint64 {
  49. if vp.err != nil {
  50. return nil
  51. }
  52. // A base value of zero makes ParseInt infer the correct base using the
  53. // string's prefix, if any.
  54. const base = 0
  55. v, err := strconv.ParseUint(vp.v, base, 64)
  56. if err != nil {
  57. vp.err = err
  58. return nil
  59. }
  60. return &v
  61. }
  62. // Err returns the last error, if any, encountered by the ValueParser.
  63. func (vp *ValueParser) Err() error {
  64. return vp.err
  65. }
上海开阖软件有限公司 沪ICP备12045867号-1