-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollback_stack.go
49 lines (39 loc) · 1.15 KB
/
rollback_stack.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
package opinionatedsagas
import "encoding/json"
type rollbackStackItem struct {
Name string `json:"name"`
Meta map[string]any `json:"meta"`
Task map[string]any `json:"task"`
}
type rollbackStack struct {
stack []*rollbackStackItem
}
func newRollbackStack() *rollbackStack {
return &rollbackStack{stack: []*rollbackStackItem{}}
}
func (s *rollbackStack) MarshalJSON() ([]byte, error) {
return json.Marshal(s.stack)
}
func (s *rollbackStack) UnmarshalJSON(data []byte) error {
if s.stack == nil {
s.stack = []*rollbackStackItem{}
}
return json.Unmarshal(data, &s.stack)
}
func (s *rollbackStack) copy() *rollbackStack {
return &rollbackStack{stack: append([]*rollbackStackItem{}, s.stack...)}
}
func (s *rollbackStack) copyAndPush(item *rollbackStackItem) *rollbackStack {
return &rollbackStack{stack: append([]*rollbackStackItem{item}, s.stack...)}
}
func (s *rollbackStack) push(item *rollbackStackItem) {
s.stack = append([]*rollbackStackItem{item}, s.stack...)
}
func (s *rollbackStack) pop() (*rollbackStackItem, bool) {
if len(s.stack) == 0 {
return nil, false
}
first, rest := s.stack[0], s.stack[1:]
s.stack = rest
return first, true
}