-
Notifications
You must be signed in to change notification settings - Fork 5
/
convert.go
107 lines (104 loc) · 2.51 KB
/
convert.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package figtree
import (
"fmt"
"strconv"
)
// dst must be a pointer type
func convertString(src string, dst interface{}) (err error) {
// allow destinations that implement the kingping.Value interface:
// https://github.com/alecthomas/kingpin/blob/v2.3.2/values.go#L30-L33
type setter interface {
Set(string) error
}
// allow destinations that implement the kingpin.Setter interface:
// https://github.com/alecthomas/kingpin/blob/v2.3.2/parsers.go#L12-L14
type setValuer interface {
SetValue(any) error
}
switch v := dst.(type) {
case *bool:
*v, err = strconv.ParseBool(src)
case *string:
*v = src
case *int:
var tmp int64
// this is a cheat, we only know int is at least 32 bits
// but we have to make a compromise here
tmp, err = strconv.ParseInt(src, 10, 32)
*v = int(tmp)
case *int8:
var tmp int64
tmp, err = strconv.ParseInt(src, 10, 8)
*v = int8(tmp)
case *int16:
var tmp int64
tmp, err = strconv.ParseInt(src, 10, 16)
*v = int16(tmp)
case *int32:
var tmp int64
tmp, err = strconv.ParseInt(src, 10, 32)
*v = int32(tmp)
case *int64:
var tmp int64
tmp, err = strconv.ParseInt(src, 10, 64)
*v = tmp
case *uint:
var tmp uint64
// this is a cheat, we only know uint is at least 32 bits
// but we have to make a compromise here
tmp, err = strconv.ParseUint(src, 10, 32)
*v = uint(tmp)
case *uint8:
var tmp uint64
tmp, err = strconv.ParseUint(src, 10, 8)
*v = uint8(tmp)
case *uint16:
var tmp uint64
tmp, err = strconv.ParseUint(src, 10, 16)
*v = uint16(tmp)
case *uint32:
var tmp uint64
tmp, err = strconv.ParseUint(src, 10, 32)
*v = uint32(tmp)
case *uint64:
var tmp uint64
tmp, err = strconv.ParseUint(src, 10, 64)
*v = tmp
// hmm, collides with uint8
// case *byte:
// tmp := []byte(src)
// if len(tmp) == 1 {
// *v = tmp[0]
// } else {
// err = fmt.Errorf("Cannot convert string %q to byte, length: %d", src, len(tmp))
// }
// hmm, collides with int32
// case *rune:
// tmp := []rune(src)
// if len(tmp) == 1 {
// *v = tmp[0]
// } else {
// err = fmt.Errorf("Cannot convert string %q to rune, lengt: %d", src, len(tmp))
// }
case *float32:
var tmp float64
tmp, err = strconv.ParseFloat(src, 32)
*v = float32(tmp)
case *float64:
var tmp float64
tmp, err = strconv.ParseFloat(src, 64)
*v = tmp
case *any:
*v = src
case setter:
return v.Set(src)
case setValuer:
return v.SetValue(src)
default:
err = fmt.Errorf("Cannot convert string %q to type %T", src, dst)
}
if err != nil {
return err
}
return nil
}