forked from cubicdaiya/gonp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatch.go
106 lines (92 loc) · 1.73 KB
/
patch.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
package gonp
import (
"container/list"
"fmt"
)
// Patch applies SES between a and b to seq
func (diff *Diff[T]) Patch(seq []T) []T {
if diff.ed == 0 {
return seq
}
l := list.New()
for _, e := range seq {
l.PushBack(e)
}
le := l.Front()
for _, e := range diff.ses {
switch e.typ {
case SesDelete:
lea := le.Next()
l.Remove(le)
le = lea
case SesAdd:
if le == nil {
le = l.PushBack(e.elem)
le = le.Next()
} else {
l.InsertBefore(e.elem, le)
}
case SesCommon:
le = le.Next()
}
}
r := make([]T, 0, l.Len())
for e := l.Front(); e != nil; e = e.Next() {
r = append(r, e.Value.(T))
}
return r
}
// UniPatch applies unified format difference between a and b to seq
func (diff *Diff[T]) UniPatch(seq []T, uniHunks []UniHunk[T]) ([]T, error) {
if diff.ed == 0 {
return seq, nil
}
if len(uniHunks) == 0 {
return []T{}, fmt.Errorf("invalid difference")
}
l := list.New()
for _, e := range seq {
l.PushBack(e)
}
le := l.Front()
for i := 0; i < uniHunks[0].a-1; i++ {
if le == nil {
return []T{}, fmt.Errorf("invalid difference")
}
le = le.Next()
}
p := 0
for _, h := range uniHunks {
if p != 0 {
for i := 0; i < h.a-p-1; i++ {
if le == nil {
return []T{}, fmt.Errorf("invalid difference")
}
le = le.Next()
}
}
for _, e := range h.changes {
switch e.typ {
case SesDelete:
lea := le.Next()
l.Remove(le)
le = lea
case SesAdd:
if le == nil {
le = l.PushBack(e.elem)
le = le.Next()
} else {
l.InsertBefore(e.elem, le)
}
case SesCommon:
le = le.Next()
}
}
p = h.a + h.b - 1
}
r := make([]T, 0, l.Len())
for e := l.Front(); e != nil; e = e.Next() {
r = append(r, e.Value.(T))
}
return r, nil
}