Skip to content

Commit

Permalink
fix: bound check on patch insert
Browse files Browse the repository at this point in the history
Closes #26
  • Loading branch information
wI2L committed Nov 11, 2024
1 parent 2399596 commit ea38423
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 6 deletions.
4 changes: 2 additions & 2 deletions differ.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ func (d *Differ) compareArraysLCS(ptr pointer, src, tgt []interface{}, doc strin

adjust := func(i int) int {
// Adjust indice considering add and remove
// operations that precede.
// operations that precede it.
return i + add - remove
}

Expand Down Expand Up @@ -483,7 +483,7 @@ func (d *Differ) add(path string, v interface{}, doc string, lcs bool) {
if !lcs {
d.patch = d.patch.append(OperationMove, op.Path, path, v, v, 0)
} else {
d.patch = d.patch.prepend(d.snapshotPatchLen, OperationMove, op.Path, path, v, v, 0)
d.patch = d.patch.insert(d.snapshotPatchLen, OperationMove, op.Path, path, v, v, 0)
}
}
return
Expand Down
3 changes: 1 addition & 2 deletions hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ func (h *hasher) sortArray(a []interface{}) {
return 1
} else if d1 < d2 {
return -1
} else {
return 0
}
return 0
})
}
7 changes: 5 additions & 2 deletions operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ func (p *Patch) append(typ string, from, path string, src, tgt interface{}, vl i
})
}

func (p *Patch) prepend(startIdx int, typ string, from, path string, src, tgt interface{}, vl int) Patch {
func (p *Patch) insert(pos int, typ string, from, path string, src, tgt interface{}, vl int) Patch {
if pos > len(*p) {
return p.append(typ, from, path, src, tgt, vl)
}
op := Operation{
Type: typ,
From: from,
Expand All @@ -127,7 +130,7 @@ func (p *Patch) prepend(startIdx int, typ string, from, path string, src, tgt in
Value: tgt,
valueLen: vl,
}
return append((*p)[:startIdx], append([]Operation{op}, (*p)[startIdx:]...)...)
return append((*p)[:pos], append([]Operation{op}, (*p)[pos:]...)...)
}

func (p *Patch) jsonLength() int {
Expand Down
5 changes: 5 additions & 0 deletions operation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ func TestPatch_jsonLength(t *testing.T) {
})
}

func Test_issue26(_ *testing.T) {
p := new(Patch)
p.insert(6, OperationAdd, emptyPointer, "/a", nil, 42, 0)
}

func typeNilIface() interface{} {
var i *int
var p interface{}
Expand Down

0 comments on commit ea38423

Please sign in to comment.