-
-
Notifications
You must be signed in to change notification settings - Fork 355
/
strings.go
127 lines (101 loc) · 1.96 KB
/
strings.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package app
import (
"fmt"
"io"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/maxence-charriere/go-app/v9/pkg/errors"
)
func toString(v interface{}) string {
switch v := v.(type) {
case string:
return v
case []byte:
return btos(v)
case int:
return strconv.Itoa(v)
case float64:
return strconv.FormatFloat(v, 'f', 4, 64)
case bool:
return strconv.FormatBool(v)
case nil:
return ""
default:
return fmt.Sprint(v)
}
}
func toPath(v ...interface{}) string {
var b strings.Builder
for _, o := range v {
s := toString(o)
if s == "" {
continue
}
b.WriteByte('/')
b.WriteString(s)
}
return b.String()
}
func writeIndent(w io.Writer, indent int) {
for i := 0; i < indent*2; i++ {
w.Write([]byte(" "))
}
}
func ln() []byte {
return []byte("\n")
}
func btos(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func pxToString(px int) string {
return strconv.Itoa(px) + "px"
}
func stringTo(s string, v interface{}) error {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
return errors.New("receiver in not a pointer").Tag("receiver-type", val.Type())
}
val = val.Elem()
switch val.Kind() {
case reflect.String:
val.SetString(s)
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64:
i, _ := strconv.ParseInt(s, 10, 0)
val.SetInt(i)
case reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64:
i, _ := strconv.ParseUint(s, 10, 0)
val.SetUint(i)
case reflect.Float64:
f, _ := strconv.ParseFloat(s, 64)
val.SetFloat(f)
case reflect.Float32:
f, _ := strconv.ParseFloat(s, 32)
val.SetFloat(f)
default:
return errors.New("string cannot be converted to receiver type").
Tag("string", s).
Tag("receiver-type", val.Type())
}
return nil
}
// AppendClass adds c to the given class string.
func AppendClass(class, c string) string {
if c == "" {
return class
}
if class != "" {
class += " "
}
class += c
return class
}