-
Notifications
You must be signed in to change notification settings - Fork 1
/
ADOL_chpater15.go
159 lines (143 loc) · 2.54 KB
/
ADOL_chpater15.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"fmt"
"math"
"encoding/json"
)
var oldFileStr = []byte(`[
{
"key": 1,
"value": "what"
},
{
"key": 6,
"value": "ever"
},
{
"key": 10,
"value": "value"
},
{
"key": 4294967295,
"value": "sentry"
}
]`)
var transactionFileStr = []byte(`[
{
"key": 1,
"value": "???",
"operation": "update"
},
{
"key": 1,
"value": "lastUpdate",
"operation": "update"
},
{
"key": 5,
"value": "insertV",
"operation": "insert"
},
{
"key": 7,
"value": "insert7",
"operation": "insert"
},
{
"key": 10,
"value": "lastUpdate",
"operation": "delete"
},
{
"key": 4294967295,
"value": "sentry",
"operation": "set_abnormal"
}
]`)
type Record struct {
Key uint32
Value string
}
func (r *Record) norm() bool {
return r.Key < math.MaxUint32
}
func (t *Transaction) norm() bool {
return t.Key < math.MaxUint32
}
func (t *Transaction) hasOp(s string) bool {
return t.Operation == s
}
type Transaction struct {
Record
Operation string
}
func (x *Record) Update(y Transaction) {
if x.norm() && x.Key == y.Key && y.hasOp("update") {
// do update
x.Value = y.Value
}
}
func (x *Record) Delete(y Transaction) {
if x.norm() && x.Key == y.Key && y.hasOp("delete") {
// do update
x.Key = math.MaxUint32
}
}
func (x *Record) Insert(y Transaction) {
if !x.norm() && y.hasOp("insert") {
x.Key = y.Key
x.Value = y.Value
}
}
func (x *Record) SetAbnorm() {
x.Key = math.MaxUint32
}
func execTrsactions(oldFile []Record, transactions []Transaction) (newFile []Record) {
xf, yf := 0, 0
x, y := oldFile[xf], transactions[yf]
for x.norm() || y.norm() {
var ckey uint32
var xx Record
if x.Key <= y.Key {
ckey = x.Key
xx.Key = x.Key
xx.Value = x.Value
xf++
x = oldFile[xf]
} else {
ckey = y.Key
xx.SetAbnorm()
}
for y.Key == ckey {
if y.hasOp("update") && xx.norm() {
xx.Update(y)
}
if y.hasOp("delete") && xx.norm() {
xx.Delete(y)
}
if y.hasOp("insert") && !xx.norm() {
xx.Insert(y)
}
if y.hasOp("insert") == xx.norm() {
fmt.Errorf("error case")
}
yf++
y = transactions[yf]
}
if xx.norm() {
newFile = append(newFile, xx)
}
}
newFile = append(newFile, x)
return newFile
}
func main() {
var oldFile []Record
json.Unmarshal(oldFileStr, &oldFile)
fmt.Println(oldFile)
var transactions []Transaction
json.Unmarshal(transactionFileStr, &transactions)
fmt.Println(transactions)
newfile := execTrsactions(oldFile, transactions)
fmt.Println(newfile)
}