blob: fe2355d3c6ffe5b378dc3a6df844cf7a7dc00c45 [file] [log] [blame]
khenaidood948f772021-08-11 17:49:24 -04001// 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
14package util
15
16import (
17 "strconv"
18)
19
20// TODO(mdlayher): util packages are an anti-pattern and this should be moved
21// somewhere else that is more focused in the future.
22
23// A ValueParser enables parsing a single string into a variety of data types
24// in a concise and safe way. The Err method must be invoked after invoking
25// any other methods to ensure a value was successfully parsed.
26type ValueParser struct {
27 v string
28 err error
29}
30
31// NewValueParser creates a ValueParser using the input string.
32func NewValueParser(v string) *ValueParser {
33 return &ValueParser{v: v}
34}
35
36// Int interprets the underlying value as an int and returns that value.
37func (vp *ValueParser) Int() int { return int(vp.int64()) }
38
39// PInt64 interprets the underlying value as an int64 and returns a pointer to
40// that value.
41func (vp *ValueParser) PInt64() *int64 {
42 if vp.err != nil {
43 return nil
44 }
45
46 v := vp.int64()
47 return &v
48}
49
50// int64 interprets the underlying value as an int64 and returns that value.
51// TODO: export if/when necessary.
52func (vp *ValueParser) int64() int64 {
53 if vp.err != nil {
54 return 0
55 }
56
57 // A base value of zero makes ParseInt infer the correct base using the
58 // string's prefix, if any.
59 const base = 0
60 v, err := strconv.ParseInt(vp.v, base, 64)
61 if err != nil {
62 vp.err = err
63 return 0
64 }
65
66 return v
67}
68
69// PUInt64 interprets the underlying value as an uint64 and returns a pointer to
70// that value.
71func (vp *ValueParser) PUInt64() *uint64 {
72 if vp.err != nil {
73 return nil
74 }
75
76 // A base value of zero makes ParseInt infer the correct base using the
77 // string's prefix, if any.
78 const base = 0
79 v, err := strconv.ParseUint(vp.v, base, 64)
80 if err != nil {
81 vp.err = err
82 return nil
83 }
84
85 return &v
86}
87
88// Err returns the last error, if any, encountered by the ValueParser.
89func (vp *ValueParser) Err() error {
90 return vp.err
91}