-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
117 lines (112 loc) · 2.56 KB
/
string.go
File metadata and controls
117 lines (112 loc) · 2.56 KB
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
108
109
110
111
112
113
114
115
116
117
// Copyright (c) 2013-2021 KIDTSUNAMI
// Author: alex@kidtsunami.com
package config
import (
"encoding/hex"
"fmt"
"reflect"
"strconv"
"strings"
)
type Stringer interface {
String() string
}
func toString(t any) string {
switch v := t.(type) {
case Stringer:
return v.String()
case string:
return v
case *string:
return *v
case []byte:
return string(v)
default:
if s, err := toRawString(t); err == nil {
return s
}
return fmt.Sprintf("%v", t)
}
}
func toRawString(t interface{}) (string, error) {
val := reflect.Indirect(reflect.ValueOf(t))
if !val.IsValid() {
return "", nil
}
typ := val.Type()
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(val.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(val.Uint(), 10), nil
case reflect.Float32, reflect.Float64:
return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil
case reflect.String:
return val.String(), nil
case reflect.Bool:
return strconv.FormatBool(val.Bool()), nil
case reflect.Array:
if typ.Elem().Kind() != reflect.Uint8 {
b := strings.Builder{}
for i, l := 0, val.Len(); i < l; i++ {
v, err := toRawString(val.Index(i).Interface())
if err != nil {
return "", err
}
if b.Len() > 0 {
b.WriteByte(',')
}
b.WriteString(v)
}
return b.String(), nil
}
// [...]byte
var b []byte
if val.CanAddr() {
b = val.Slice(0, val.Len()).Bytes()
} else {
b = make([]byte, val.Len())
reflect.Copy(reflect.ValueOf(b), val)
}
return hex.EncodeToString(b), nil
case reflect.Slice:
if typ.Elem().Kind() != reflect.Uint8 {
b := strings.Builder{}
for i, l := 0, val.Len(); i < l; i++ {
v, err := toRawString(val.Index(i).Interface())
if err != nil {
return "", err
}
if b.Len() > 0 {
b.WriteByte(',')
}
b.WriteString(v)
}
return b.String(), nil
}
// []byte
b := val.Bytes()
return hex.EncodeToString(b), nil
case reflect.Map:
b := strings.Builder{}
for _, e := range val.MapKeys() {
k, err := toRawString(e.Interface())
if err != nil {
return "", err
}
v := val.MapIndex(e)
vv, err := toRawString(v.Interface())
if err != nil {
return "", err
}
if b.Len() > 0 {
b.WriteByte(',')
}
b.WriteString(k)
b.WriteByte('=')
b.WriteString(vv)
}
return b.String(), nil
}
return "", fmt.Errorf("no method for converting type %s (%v) to string", typ.String(), val.Kind())
}