sergi / go-diff

Diff, match and patch text in Go
MIT License
1.81k stars 207 forks source link

PatchApply panics with slice bounds out of range #132

Open mwain opened 2 years ago

mwain commented 2 years ago

The following code panics when using PatchApply

func main() {
    dmp := diffmatchpatch.New()
    patches, _ := dmp.PatchFromText("@@ -1,2 +1,3 @@\n %E2%98%9E \n+r\n")
    fmt.Println(dmp.PatchToText(patches))

    s, _ := dmp.PatchApply(patches, "☞ 𝗢𝗥𝗗𝗘𝗥 ")
    fmt.Println(fmt.Sprintf("%q", s))
}
panic: runtime error: slice bounds out of range [:35] with length 33

goroutine 1 [running]:
github.com/sergi/go-diff/diffmatchpatch.(*DiffMatchPatch).PatchApply(0x14000109ef8, {0x14000078200?, 0x1, 0x1?}, {0x102d6650a, 0x19})
        /Users/michael/go/pkg/mod/github.com/sergi/go-diff@v1.2.0/diffmatchpatch/patch.go:306 +0x998
main.main()
        /Users/michael/code/playground/scratch/main.go:14 +0xf0
exit status 2

It looks like its finding the wrong start location here - https://github.com/sergi/go-diff/blob/master/diffmatchpatch/patch.go#L265 E.g: this prints 25...

func main() {
    dmp := diffmatchpatch.New()
    fmt.Println(dmp.MatchMain("\x01\x02\x03\x04☞ 𝗢𝗥𝗗𝗘𝗥 \x01\x02\x03\x04", "☞ \x01\x02\x03\x04", 4))
}