-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_types.go
62 lines (54 loc) · 1.58 KB
/
utils_types.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
54
55
56
57
58
59
60
61
62
package dnsutils
import (
"strconv"
"strings"
"github.com/miekg/dns"
"github.com/mimuret/intcast"
"golang.org/x/exp/constraints"
)
// ConvertStringToType returns uint16 dns rrtype by string
// If it failed to parse, returns ErrInvalid
func ConvertStringToType(s string) (uint16, error) {
return ConvertToStringToNumber(dns.StringToType, "TYPE", s)
}
// ConvertStringToClass returns dns.Class by string
// If it failed to parse, returns ErrInvalid
func ConvertStringToClass(s string) (dns.Class, error) {
class, err := ConvertToStringToNumber(dns.StringToClass, "CLASS", s)
return dns.Class(class), err
}
func ConvertToStringToNumber[T constraints.Integer](def map[string]T, prefix, s string) (T, error) {
var (
t T
ok bool
)
if t, ok = def[s]; ok {
return t, nil
}
if strings.HasPrefix(s, prefix) {
v := strings.TrimLeft(s, prefix)
res, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return 0, ErrInvalid
}
if err := intcast.Cast(res, &t); err != nil {
return 0, ErrInvalid
}
return t, nil
}
return 0, ErrInvalid
}
// ConvertTypeToString returns RRType string by uint16 dns rrtype.
func ConvertTypeToString(i uint16) string {
return ConvertNumberToString(dns.TypeToString, "TYPE", i)
}
// ConvertClassToString returns DNS Class string by dns.Class
func ConvertClassToString(i dns.Class) string {
return ConvertNumberToString(dns.ClassToString, "CLASS", uint16(i))
}
func ConvertNumberToString[T constraints.Integer](def map[T]string, prefix string, i T) string {
if s, ok := def[i]; ok {
return s
}
return prefix + strconv.FormatUint(uint64(i), 10)
}