-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_proxy.go
114 lines (89 loc) · 2.11 KB
/
access_proxy.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
package main
import (
"fmt"
"log"
)
type User struct {
Name *string
ID int
}
type AccessProxy struct {
original User
data *User
changedFields map[string]struct{}
changeSigs []changeSig
}
func NewAccessProxy(data *User) *AccessProxy {
return &AccessProxy{
data: data,
original: *data,
changedFields: make(map[string]struct{}),
}
}
type changeSig interface {
fieldName() string
}
type nameChangeSig struct {
val *string
}
func (s nameChangeSig) fieldName() string { return "Name" }
type idChangeSig struct {
val int
}
func (s idChangeSig) fieldName() string { return "ID" }
func (p *AccessProxy) GetName() *string {
copy := *p.data.Name
return ©
}
func (p *AccessProxy) SetName(val *string) {
p.changeSigs = append(p.changeSigs, nameChangeSig{val: val})
}
func (p *AccessProxy) GetID() int {
return p.data.ID
}
func (p *AccessProxy) SetID(val int) {
p.changeSigs = append(p.changeSigs, idChangeSig{val: val})
}
func (p *AccessProxy) rollback() {
*p.data = p.original
}
func (p *AccessProxy) ApplyChanges() error {
for _, s := range p.changeSigs {
if _, alreadyChanged := p.changedFields[s.fieldName()]; alreadyChanged {
p.rollback()
return fmt.Errorf("duplicate changes detected for field `%s`", s.fieldName())
}
p.changedFields[s.fieldName()] = struct{}{}
switch sig := s.(type) {
case nameChangeSig:
p.data.Name = sig.val
case idChangeSig:
p.data.ID = sig.val
default:
// should not happen
return fmt.Errorf("unknown signal: %+v", sig)
}
}
return nil
}
func main() {
usr := &User{Name: toPointer("name"), ID: 1}
ap := NewAccessProxy(usr)
ap.SetName(toPointer("changed name"))
ap.SetID(2)
// ap.SetName(toPointer("changed 2 name")) // un comment to cause an error
err := ap.ApplyChanges()
if err != nil {
fmt.Printf("failed: usr: %+v\n", usr)
fmt.Println("usr.Name:", *usr.Name)
log.Fatal(err)
}
fmt.Printf("usr: %+v\n", usr)
fmt.Println("usr.Name:", *usr.Name)
n := ap.GetName()
*n = "BAD CHANGE"
fmt.Printf("%s\n", *usr.Name) // should not be changed to BAD CHANGE
}
func toPointer[T any](t T) *T {
return &t
}