forked from OneOfOne/genh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptr.go
57 lines (44 loc) · 793 Bytes
/
ptr.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
package genh
import (
"encoding/json"
)
func Ptr[T any](v T) *T {
return &v
}
func PtrVal[T any](v *T) (_ T) {
if v == nil {
return
}
return *v
}
func Zero[T any]() (_ T) { return }
type PtrTo[T any] struct {
v *T
}
func (p *PtrTo[T]) Set(v T) {
p.v = &v
}
func (p *PtrTo[T]) Unset() {
p.v = nil
}
func (p *PtrTo[T]) IsSet() bool {
return p.v != nil
}
func (p *PtrTo[T]) Val() T {
if p.v != nil {
return *p.v
}
return Zero[T]()
}
func (p PtrTo[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(p.v)
}
func (p *PtrTo[T]) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &p.v)
}
func (p PtrTo[T]) MarshalBinary() ([]byte, error) {
return MarshalMsgpack(p.v)
}
func (p *PtrTo[T]) UnmarshalBinary(b []byte) error {
return UnmarshalMsgpack(b, &p.v)
}