From 60af5a5e5c58c2ea0c6faf8a30246d74c7bdd158 Mon Sep 17 00:00:00 2001 From: Evan Phoenix Date: Tue, 20 Apr 2021 17:40:28 -0700 Subject: [PATCH] Fix zero sized document crash --- patch.go | 4 ++++ patch_test.go | 10 +++++++++- v5/patch.go | 8 ++++++-- v5/patch_test.go | 9 +++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/patch.go b/patch.go index f185a45..1829854 100644 --- a/patch.go +++ b/patch.go @@ -721,6 +721,10 @@ func (p Patch) Apply(doc []byte) ([]byte, error) { // ApplyIndent mutates a JSON document according to the patch, and returns the new // document indented. func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { + if len(doc) == 0 { + return doc, nil + } + var pd container if doc[0] == '[' { pd = &partialArray{} diff --git a/patch_test.go b/patch_test.go index 40c9b26..22db16f 100644 --- a/patch_test.go +++ b/patch_test.go @@ -56,6 +56,13 @@ func repeatedA(r int) string { } var Cases = []Case{ + { + ``, + `[ + { "op": "add", "path": "/baz", "value": "qux" } + ]`, + ``, + }, { `{ "foo": "bar"}`, `[ @@ -518,8 +525,9 @@ func TestAdd(t *testing.T) { key: "-1", val: lazyNode{}, arr: partialArray{}, + err: "Unable to access invalid index: -1: invalid index referenced", + rejectNegativeIndicies: true, - err: "Unable to access invalid index: -1: invalid index referenced", }, } for _, tc := range testCases { diff --git a/v5/patch.go b/v5/patch.go index fc860ac..f24e9d5 100644 --- a/v5/patch.go +++ b/v5/patch.go @@ -27,7 +27,7 @@ var ( startObject = json.Delim('{') endObject = json.Delim('}') startArray = json.Delim('[') - endArray = json.Delim(']') + endArray = json.Delim(']') ) var ( @@ -57,7 +57,7 @@ type Patch []Operation type partialDoc struct { keys []string - obj map[string]*lazyNode + obj map[string]*lazyNode } type partialArray []*lazyNode @@ -1026,6 +1026,10 @@ func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { // ApplyIndentWithOptions mutates a JSON document according to the patch and the passed in ApplyOptions. // It returns the new document indented. func (p Patch) ApplyIndentWithOptions(doc []byte, indent string, options *ApplyOptions) ([]byte, error) { + if len(doc) == 0 { + return doc, nil + } + var pd container if doc[0] == '[' { pd = &partialArray{} diff --git a/v5/patch_test.go b/v5/patch_test.go index e7e5be3..30fa7d5 100644 --- a/v5/patch_test.go +++ b/v5/patch_test.go @@ -90,6 +90,15 @@ func repeatedA(r int) string { } var Cases = []Case{ + { + ``, + `[ + { "op": "add", "path": "/baz", "value": "qux" } + ]`, + ``, + false, + false, + }, { `{ "foo": "bar"}`, `[