/
hash_maybe.go
98 lines (81 loc) · 1.82 KB
/
hash_maybe.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
package prototyp
import (
"database/sql/driver"
"encoding/hex"
)
// HashMaybe is a nullable Hash value useful for database fields which accept NULL type.
type HashMaybe struct {
Hash
// IsAssigned=false means value is nil. IsAssigned=true means value in .Hash is the value.
IsAssigned bool
}
func HashMaybeFromString(s string) HashMaybe {
if s == "" {
return HashMaybe{}
} else {
return HashMaybe{
Hash: HashFromString(s),
IsAssigned: true,
}
}
}
func (h *HashMaybe) SetValue(hash Hash) {
h.Hash = hash
h.IsAssigned = true
}
func (h *HashMaybe) SetNil() {
h.Hash = ""
h.IsAssigned = false
}
// UnmarshalText implements encoding.TextMarshaler.
func (h HashMaybe) MarshalText() ([]byte, error) {
return []byte(h.String()), nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (h *HashMaybe) UnmarshalText(src []byte) error {
t := string(src)
if t == "null" || t == "" {
return nil
}
*h = HashMaybeFromString(t)
return nil
}
func (h HashMaybe) Value() (driver.Value, error) {
if h.IsAssigned {
s := h.String()
if len(s) < 2 {
return []byte{}, nil
}
return hex.DecodeString(s[2:])
}
return nil, nil
}
func (h *HashMaybe) Scan(src interface{}) error {
h.IsAssigned = false
if src == nil {
return nil
}
h.Hash = HashFromBytes(src.([]byte))
h.IsAssigned = true
return nil
}
func (h *HashMaybe) ExtensionType() int8 {
return 11
}
func (h *HashMaybe) Len() int {
return len(h.Hash.String())
}
func (h *HashMaybe) MarshalBinaryTo(b []byte) error {
copy(b[:], h.Hash.String())
return nil
}
func (h *HashMaybe) UnmarshalBinary(b []byte) error {
*h = HashMaybeFromString(string(b))
return nil
}
func ToHashMaybe(h Hexer) HashMaybe {
return HashMaybeFromString(h.Hex())
}
func BytesToHashMaybe(src []byte) HashMaybe {
return HashMaybeFromString("0x" + hex.EncodeToString(src))
}