-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtype.go
126 lines (101 loc) · 1.87 KB
/
type.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
package stream
import (
"reflect"
"strings"
"github.com/google/uuid"
)
type Type string
func NewType[T any](v ...T) (Type, error) {
var s string
var r reflect.Type
if len(v) != 0 {
switch x := any(v[0]).(type) {
case string:
r = reflect.TypeOf(x)
default:
r = reflect.TypeOf(x)
}
} else {
var t T
r = reflect.TypeOf(t)
s = r.Name()
}
switch r.Kind() {
case reflect.Pointer:
s = r.Elem().Name()
case reflect.String:
if s = "string"; len(v) != 0 {
s = any(v[0]).(string)
}
default:
s = r.Name()
}
if n, ok := Type(s).reformat(); ok {
return n, nil
}
return "", Err("type can not be empty string")
}
func MustType[T any](v ...T) Type {
t, err := NewType[T](v...)
if err != nil {
panic(err)
}
return t
}
func (t Type) ID(s string) ID {
return ID{
typ: t,
uuid: NewUUID(s),
}
}
func (t Type) Rename(s string) Type {
if v, ok := Type(s).reformat(); ok {
return v
}
return t
}
func (t Type) Hash() UUID {
return NewUUID(t.String())
}
func (t Type) String() string {
return string(t)
}
func (t Type) IsEmpty() bool {
return t == ""
}
func (t Type) CutPrefix(of Type) Type {
a, b := t.String(), of.String()
if strings.Index(a, b) == -1 {
return t
}
return Type(strings.Replace(a, b, "", 1))
}
func (t Type) ToLower() string {
return strings.ToLower(string(t))
}
func (t Type) reformat() (Type, bool) {
s := string(t)
if s = strings.ReplaceAll(s, " ", ""); len(s) == 0 {
return "", false
}
return Type(strings.Title(s)), true
}
type UUID struct{ id uuid.UUID }
func NewUUID(s string) UUID {
if s == "" {
return UUID{}
}
return UUID{uuid.NewSHA1(uuid.NameSpaceDNS, []byte(s))}
}
func (u UUID) String() string {
return u.id.String()
}
func (u UUID) Short() string {
return u.String()[:8]
}
func (u UUID) Is(n string) bool {
return u.id.String() == n
}
func (u UUID) IsEmpty() bool {
return u.id.Version() == 0
}