cubefs
91 строка · 2.4 Кб
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
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 {
27v string
28err error
29}
30
31// NewValueParser creates a ValueParser using the input string.
32func NewValueParser(v string) *ValueParser {
33return &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 {
42if vp.err != nil {
43return nil
44}
45
46v := vp.int64()
47return &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 {
53if vp.err != nil {
54return 0
55}
56
57// A base value of zero makes ParseInt infer the correct base using the
58// string's prefix, if any.
59const base = 0
60v, err := strconv.ParseInt(vp.v, base, 64)
61if err != nil {
62vp.err = err
63return 0
64}
65
66return 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 {
72if vp.err != nil {
73return nil
74}
75
76// A base value of zero makes ParseInt infer the correct base using the
77// string's prefix, if any.
78const base = 0
79v, err := strconv.ParseUint(vp.v, base, 64)
80if err != nil {
81vp.err = err
82return nil
83}
84
85return &v
86}
87
88// Err returns the last error, if any, encountered by the ValueParser.
89func (vp *ValueParser) Err() error {
90return vp.err
91}
92