-
-
Notifications
You must be signed in to change notification settings - Fork 353
/
strings.go
149 lines (120 loc) · 2.46 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package app
import (
"encoding/json"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"github.com/maxence-charriere/go-app/v10/pkg/errors"
)
func toString(v any) string {
switch v := v.(type) {
case string:
return v
case []byte:
return string(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 ...any) 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++ {
io.WriteString(w, " ")
}
}
func stringTo(s string, v any) error {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
return errors.New("receiver in not a pointer").WithTag("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").
WithTag("string", s).
WithTag("receiver-type", val.Type())
}
return nil
}
// AppendClass adds values to the given class string.
func AppendClass(class string, v ...string) string {
var b strings.Builder
b.WriteString(strings.TrimSpace(class))
for _, c := range v {
c = strings.TrimSpace(c)
if c == "" {
continue
}
if b.Len() != 0 {
b.WriteByte(' ')
}
b.WriteString(c)
}
return b.String()
}
func jsonString(v any) string {
b, err := json.Marshal(v)
if err != nil {
panic(errors.New("converting value to json string failed").Wrap(err))
}
return string(b)
}
// Formats a string with the given format and values.
// It uses fmt.Sprintf when len(v) != 0.
//
// TODO: Write a faster Sprintf to use with values.
func FormatString(format string, v ...any) string {
if len(v) == 0 {
return format
}
return fmt.Sprintf(format, v...)
}
func previewText(v string) string {
if len(v) <= 80 {
return v
}
return v[:77] + "..."
}