/
number.go
53 lines (43 loc) · 821 Bytes
/
number.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// SPDX-License-Identifier: MIT
package number
import (
"fmt"
"math/bits"
"regexp"
"strconv"
constraintsext "github.com/go-playground/pkg/v5/constraints"
)
const (
pattern = `^(0|[1-9]\d*)$`
base = 10
)
var /* const */ numericRegexp *regexp.Regexp
func init() {
numericRegexp = regexp.MustCompile(pattern)
}
func ParseUint(s string) (uint, error) {
u, err := strconv.ParseUint(s, base, bits.UintSize)
if err != nil {
return 0, fmt.Errorf("failed to parse uint: %w", err)
}
return uint(u), nil
}
func MustParseUint(s string) uint {
u, err := ParseUint(s)
if err != nil {
panic(err)
}
return u
}
func IsNumeric(s string) bool {
return numericRegexp.MatchString(s)
}
func CompareInt[T constraintsext.Integer](a, b T) int {
if a == b {
return 0
}
if a < b {
return -1
}
return +1
}