-
Notifications
You must be signed in to change notification settings - Fork 22
/
uuid.go
129 lines (113 loc) · 2.35 KB
/
uuid.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
//nolint:revive
package schema
import (
"encoding/hex"
"fmt"
)
type UUIDTransformer interface {
TransformUUID(*UUID) any
}
type UUID struct {
Bytes [16]byte
Status Status
}
func (*UUID) Type() ValueType {
return TypeUUID
}
func (dst *UUID) Size() int {
return 16
}
func (dst *UUID) GetStatus() Status {
return dst.Status
}
func (dst *UUID) Equal(src CQType) bool {
if src == nil {
return false
}
s, ok := src.(*UUID)
if !ok {
return false
}
return dst.Status == s.Status && dst.Bytes == s.Bytes
}
func (dst *UUID) String() string {
if dst.Status == Present {
return hex.EncodeToString(dst.Bytes[:])
} else {
return ""
}
}
func (dst *UUID) Set(src any) error {
if src == nil {
*dst = UUID{Status: Null}
return nil
}
switch value := src.(type) {
case interface{ Get() any }:
value2 := value.Get()
if value2 != value {
return dst.Set(value2)
}
case fmt.Stringer:
value2 := value.String()
return dst.Set(value2)
case [16]byte:
*dst = UUID{Bytes: value, Status: Present}
case []byte:
if value != nil {
if len(value) != 16 {
return &ValidationError{Type: TypeUUID, Msg: "[]byte must be 16 bytes to convert to UUID", Value: value}
}
*dst = UUID{Status: Present}
copy(dst.Bytes[:], value)
} else {
*dst = UUID{Status: Null}
}
case string:
uuid, err := parseUUID(value)
if err != nil {
return err
}
*dst = UUID{Bytes: uuid, Status: Present}
case *string:
if value == nil {
*dst = UUID{Status: Null}
} else {
return dst.Set(*value)
}
default:
if originalSrc, ok := underlyingUUIDType(src); ok {
return dst.Set(originalSrc)
}
return &ValidationError{Type: TypeUUID, Msg: noConversion, Value: value}
}
return nil
}
func (dst UUID) Get() any {
switch dst.Status {
case Present:
return dst.Bytes
case Null:
return nil
default:
return dst.Status
}
}
// parseUUID converts a string UUID in standard form to a byte array.
func parseUUID(src string) (dst [16]byte, err error) {
switch len(src) {
case 36:
src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:]
case 32:
// dashes already stripped, assume valid
default:
// assume invalid.
return dst, &ValidationError{Type: TypeUUID, Msg: fmt.Sprintf("invalid %d UUID length", len(src)), Value: src}
}
buf, err := hex.DecodeString(src)
if err != nil {
return dst, err
}
copy(dst[:], buf)
return dst, err
}