Skip to content

Commit 1d4373a

Browse files
[#5] 修复越界导致的panic
1 parent 77012f8 commit 1d4373a

File tree

4 files changed

+46
-9
lines changed

4 files changed

+46
-9
lines changed

jsondiff_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,3 +182,13 @@ func eq(a, b *decode.JsonNode) bool {
182182
}
183183
return true
184184
}
185+
186+
func TestAsDiffsIssue5(t *testing.T) {
187+
json1 := `{"A": 1, "B": [1, 2, 3], "C": [1, 2]}`
188+
json2 := `{"A": 1, "B": [1, 3], "C": [2, 1], "D": 6}`
189+
diffs, err := AsDiffs([]byte(json1), []byte(json2), UseMoveOption, UseCopyOption, UseFullRemoveOption)
190+
if err != nil {
191+
t.Error("got an error", err)
192+
}
193+
fmt.Println(string(diffs))
194+
}

lcs.go

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,25 +30,21 @@ func longestCommonSubsequence(first, second []*decode.JsonNode) []*decode.JsonNo
3030
}
3131
}
3232
}
33-
// printDP(dp)
3433
start, end := len(first), len(second)
3534
cur := dp[start][end] - 1
3635
res := make([]*decode.JsonNode, cur+1)
36+
37+
// fix issue #5 (https://github.com/520MianXiangDuiXiang520/json-diff/issues/5)
3738
for cur >= 0 {
38-
if end >= 0 && start >= 0 &&
39-
dp[start][end] == dp[start][end-1] &&
40-
dp[start][end] == dp[start-1][end] {
41-
start--
42-
end--
43-
} else if end >= 0 && dp[start][end] == dp[start][end-1] {
39+
if end > 0 && dp[start][end] == dp[start][end-1] {
4440
end--
45-
} else if start >= 0 && dp[start][end] == dp[start-1][end] {
41+
} else if start > 0 && dp[start][end] == dp[start-1][end] {
4642
start--
4743
} else {
4844
res[cur] = first[start-1]
49-
cur--
5045
start--
5146
end--
47+
cur--
5248
}
5349
}
5450

options.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,9 @@ func computeUnChangeNode(container *unChangeContainer, path string, src, target
212212

213213
func computeSliceUnChange(contains *unChangeContainer, path string, src, target *decode.JsonNode) {
214214
for i, v := range src.Children {
215+
if i >= len(target.Children) {
216+
return
217+
}
215218
computeUnChangeNode(contains, fmt.Sprintf("%s/%d", path, i), v, target.Children[i])
216219
}
217220
}

test_data/getDiffTest.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,34 @@
312312
"options": [
313313
8
314314
]
315+
},
316+
{
317+
"name": "issues#5",
318+
"src": {
319+
"A": [
320+
1,
321+
2
322+
]
323+
},
324+
"patch": {
325+
"A": [
326+
2,
327+
1
328+
]
329+
},
330+
"want": [
331+
{
332+
"op": "remove",
333+
"path": "/A/0"
334+
},
335+
{
336+
"op": "add",
337+
"path": "/A/1",
338+
"value": 1
339+
}
340+
],
341+
"want-error": false,
342+
"options": []
315343
}
316344
]
317345
}

0 commit comments

Comments
 (0)