cubefs
97 строк · 2.3 Кб
1// Copyright 2018 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"os"
18"strconv"
19"strings"
20)
21
22// ParseUint32s parses a slice of strings into a slice of uint32s.
23func ParseUint32s(ss []string) ([]uint32, error) {
24us := make([]uint32, 0, len(ss))
25for _, s := range ss {
26u, err := strconv.ParseUint(s, 10, 32)
27if err != nil {
28return nil, err
29}
30
31us = append(us, uint32(u))
32}
33
34return us, nil
35}
36
37// ParseUint64s parses a slice of strings into a slice of uint64s.
38func ParseUint64s(ss []string) ([]uint64, error) {
39us := make([]uint64, 0, len(ss))
40for _, s := range ss {
41u, err := strconv.ParseUint(s, 10, 64)
42if err != nil {
43return nil, err
44}
45
46us = append(us, u)
47}
48
49return us, nil
50}
51
52// ParsePInt64s parses a slice of strings into a slice of int64 pointers.
53func ParsePInt64s(ss []string) ([]*int64, error) {
54us := make([]*int64, 0, len(ss))
55for _, s := range ss {
56u, err := strconv.ParseInt(s, 10, 64)
57if err != nil {
58return nil, err
59}
60
61us = append(us, &u)
62}
63
64return us, nil
65}
66
67// ReadUintFromFile reads a file and attempts to parse a uint64 from it.
68func ReadUintFromFile(path string) (uint64, error) {
69data, err := os.ReadFile(path)
70if err != nil {
71return 0, err
72}
73return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
74}
75
76// ReadIntFromFile reads a file and attempts to parse a int64 from it.
77func ReadIntFromFile(path string) (int64, error) {
78data, err := os.ReadFile(path)
79if err != nil {
80return 0, err
81}
82return strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
83}
84
85// ParseBool parses a string into a boolean pointer.
86func ParseBool(b string) *bool {
87var truth bool
88switch b {
89case "enabled":
90truth = true
91case "disabled":
92truth = false
93default:
94return nil
95}
96return &truth
97}
98