Playground
gnomod.toml
module = "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/myersdiff/v0" gno = "0.9" [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 751709 max_deposit = "12000000ugnot"
myersdiff.gno
// Package myersdiff computes the shortest edit script between two sequences of
// lines, using Myers' greedy algorithm: the same one git, diff and every review
// tool run to turn two documents into a list of additions and deletions.
//
// A realm that stores text and lets it be edited has two versions of it and no
// way to show what moved between them. Storing a diff instead of a snapshot is
// the usual answer, and this is the half that produces it.
//
// The cost of the search is bounded by a budget, not by the input size alone:
// see [Budget] for why a minimal diff is sometimes the wrong answer on chain.
//
// Live demo: [r/moul/x/daily/myersdiffdemo](/r/moul/x/daily/myersdiffdemo/v0).
package myersdiff
import (
"strconv"
"strings"
)
// Op is what happened to one line.
type Op int8
const (
// Delete marks a line present in a and absent from b.
Delete Op = -1
// Equal marks a line present in both, unchanged.
Equal Op = 0
// Insert marks a line absent from a and present in b.
Insert Op = 1
)
// String renders the op as the single character a unified diff uses.
func (o Op) String() string {
switch o {
case Delete:
return "-"
case Insert:
return "+"
default:
return " "
}
}
// Edit is one line of the edit script.
type Edit struct {
Op Op
Line string
}
// Script is a complete edit script turning a into b.
//
// Minimal is false when the search hit its budget and the script fell back to
// deleting everything and inserting everything. That script is still correct:
// applying it to a yields b. It is simply not the shortest one.
type Script struct {
Edits []Edit
Minimal bool
}
// Added counts inserted lines.
func (s Script) Added() int { return s.count(Insert) }
// Deleted counts deleted lines.
func (s Script) Deleted() int { return s.count(Delete) }
// Unchanged counts lines carried over untouched.
func (s Script) Unchanged() int { return s.count(Equal) }
func (s Script) count(op Op) int {
n := 0
for _, e := range s.Edits {
if e.Op == op {
n++
}
}
return n
}
// Apply replays the script against a and returns the lines it produces, which
// is b when the script came from Slices(a, b).
//
// The second return reports whether a is the document the script describes:
// every Equal and Delete edit has to match the line it consumes, and the script
// has to consume all of a. It is false for a script built against a different
// document, which is the check that makes a stored diff verifiable rather than
// merely replayable. The lines are returned either way, because they are what
// the script says and a caller deciding what to do about a mismatch usually
// wants to see both.
func (s Script) Apply(a []string) ([]string, bool) {
out := []string{}
ok := true
i := 0
for _, e := range s.Edits {
switch e.Op {
case Equal:
if i >= len(a) || a[i] != e.Line {
ok = false
}
i++
out = append(out, e.Line)
case Delete:
if i >= len(a) || a[i] != e.Line {
ok = false
}
i++
case Insert:
out = append(out, e.Line)
}
}
if i != len(a) {
ok = false
}
return out, ok
}
// DefaultBudget caps the number of rounds the search may run before it gives up
// and returns a non-minimal script. Myers' algorithm costs O((n+m)*d) where d is
// the number of differing lines, so two similar documents are cheap at any size
// and two unrelated ones are quadratic. On chain the caller picks the input, so
// the cost has to be bounded by something the caller does not control.
//
// The threshold this sets is worth stating plainly, because it is not a size:
// the default gives up past 256 changed lines, at any file size. Two 4,000-line
// documents differing in 10 lines are diffed minimally; two 300-line documents
// sharing nothing are not. A caller whose documents are large and similar is
// well inside it; a caller diffing unrelated text is always outside it and
// should pass a small budget rather than pay for the search before the
// fallback.
//
// The cost is in gas, not just in time: a search that runs to the default
// ceiling against two MaxLines documents was measured in the billions of gas
// against a 3,000,000,000 block limit during the review of this package, before
// the frontier was resized to the round ceiling. Treat a full-ceiling search as
// something to avoid rather than something to budget for.
const DefaultBudget = 256
// MaxBudget is the hard ceiling on the rounds any caller can ask for, whatever
// budget it passes.
//
// It exists because the round count, not the input size, is what the search
// allocates against: one snapshot of the frontier is kept per round so the
// script can be walked back out of them. Without the ceiling, two documents at
// MaxLines and a large budget would permit 8,192 snapshots, and the budget
// parameter would hand a caller the memory bill as a dial. The useful direction
// for a caller is downwards.
const MaxBudget = 1024
// MaxLines caps each side of the comparison. The algorithm allocates two slices
// proportional to n+m before it compares anything, so the size is checked before
// the work starts rather than discovered during it.
const MaxLines = 4096
// Lines splits a and b on "\n" and diffs them with DefaultBudget.
//
// A trailing newline produces a trailing empty line on that side, which is what
// makes "a\n" and "a" different documents here, as they are to diff(1).
func Lines(a, b string) Script {
checkLineCap(a)
checkLineCap(b)
return Slices(split(a), split(b))
}
// checkLineCap refuses an oversized document before strings.Split allocates a
// slice for it. MaxLines is checked again in Budget, for a caller that supplies
// its own slices; this is the copy that matters, because counting newlines
// allocates nothing and splitting them allocates everything.
func checkLineCap(s string) {
if s == "" {
return
}
if strings.Count(s, "\n")+1 > MaxLines {
panic("myersdiff: input exceeds MaxLines")
}
}
func split(s string) []string {
if s == "" {
return []string{}
}
return strings.Split(s, "\n")
}
// Slices diffs two line sequences with DefaultBudget.
func Slices(a, b []string) Script {
return Budget(a, b, DefaultBudget)
}
// Budget diffs two line sequences, stopping the search after at most budget
// rounds. A budget of zero or less means DefaultBudget; a budget larger than
// len(a)+len(b) is capped at it, since no minimal script is longer than that.
//
// It panics when either side exceeds MaxLines. Construction is a transaction,
// where aborting is the useful answer; reading is where totality matters, and
// every method on the resulting Script is total.
func Budget(a, b []string, budget int) Script {
if len(a) > MaxLines || len(b) > MaxLines {
panic("myersdiff: input exceeds MaxLines")
}
if budget <= 0 {
budget = DefaultBudget
}
edits, ok := search(a, b, effectiveRounds(budget, len(a), len(b)))
if !ok {
return Script{Edits: replaceAll(a, b), Minimal: false}
}
return Script{Edits: edits, Minimal: true}
}
func replaceAll(a, b []string) []Edit {
edits := []Edit{}
for _, line := range a {
edits = append(edits, Edit{Op: Delete, Line: line})
}
for _, line := range b {
edits = append(edits, Edit{Op: Insert, Line: line})
}
return edits
}
// effectiveRounds is how many rounds the search may run: the caller's budget,
// defaulted when unset and capped by both MaxBudget and n+m, since no minimal
// script is longer than n+m.
func effectiveRounds(budget, n, m int) int {
if budget <= 0 {
budget = DefaultBudget
}
if budget > MaxBudget {
budget = MaxBudget
}
if budget > n+m {
budget = n + m
}
return budget
}
// search runs the greedy forward pass, recording one snapshot of the frontier
// per round, then walks the snapshots backwards into an edit script. It reports
// false when the budget ran out before the two ends met.
func search(a, b []string, budget int) ([]Edit, bool) {
n := len(a)
m := len(b)
maxD := budget
// At round d only the diagonals -d..d are live, and d never exceeds maxD,
// so the frontier is sized by the round ceiling rather than by the input.
// That is what keeps a snapshot small when two large documents are being
// compared under a small budget.
offset := maxD + 1
v := make([]int, 2*maxD+3)
trace := [][]int{}
for d := 0; d <= maxD; d++ {
snapshot := make([]int, len(v))
copy(snapshot, v)
trace = append(trace, snapshot)
for k := -d; k <= d; k += 2 {
var x int
// Move down (an insertion) when the diagonal below reaches further,
// or when there is no diagonal to the left to come from at all.
if k == -d || (k != d && v[offset+k-1] < v[offset+k+1]) {
x = v[offset+k+1]
} else {
x = v[offset+k-1] + 1
}
y := x - k
for x < n && y < m && a[x] == b[y] {
x++
y++
}
v[offset+k] = x
if x >= n && y >= m {
return backtrack(a, b, trace, offset), true
}
}
}
return nil, false
}
// backtrack walks the recorded frontiers from the end back to the origin. Each
// snapshot is the state before its own round, so the same rule that chose a move
// forwards identifies the predecessor backwards.
func backtrack(a, b []string, trace [][]int, offset int) []Edit {
x := len(a)
y := len(b)
rev := []Edit{}
for d := len(trace) - 1; d >= 0; d-- {
v := trace[d]
k := x - y
var prevK int
if k == -d || (k != d && v[offset+k-1] < v[offset+k+1]) {
prevK = k + 1
} else {
prevK = k - 1
}
prevX := v[offset+prevK]
prevY := prevX - prevK
for x > prevX && y > prevY {
rev = append(rev, Edit{Op: Equal, Line: a[x-1]})
x--
y--
}
if d > 0 {
if x == prevX {
rev = append(rev, Edit{Op: Insert, Line: b[prevY]})
} else {
rev = append(rev, Edit{Op: Delete, Line: a[prevX]})
}
}
x = prevX
y = prevY
}
edits := make([]Edit, len(rev))
for i, e := range rev {
edits[len(rev)-1-i] = e
}
return edits
}
// Hunk is a contiguous run of the script worth printing: every change, plus up
// to context unchanged lines on each side of it.
//
// AStart and BStart are 1-based line numbers. When a side contributes no lines
// at all, its start is the number of the line before the hunk and its length is
// zero, which is what diff(1) prints for a pure insertion into an empty file.
type Hunk struct {
AStart int
ALines int
BStart int
BLines int
Edits []Edit
}
// Header renders the @@ line of a unified diff.
func (h Hunk) Header() string {
return "@@ -" + rangeOf(h.AStart, h.ALines) + " +" + rangeOf(h.BStart, h.BLines) + " @@"
}
func rangeOf(start, length int) string {
if length == 1 {
return strconv.Itoa(start)
}
return strconv.Itoa(start) + "," + strconv.Itoa(length)
}
// Hunks groups a script into the runs a unified diff prints, with context
// unchanged lines around each change. A negative context is treated as zero; a
// script with no changes produces no hunks.
func Hunks(s Script, context int) []Hunk {
if context < 0 {
context = 0
}
edits := s.Edits
// aPos[i] and bPos[i] are how many lines of each side precede edit i.
aPos := make([]int, len(edits)+1)
bPos := make([]int, len(edits)+1)
for i, e := range edits {
aPos[i+1] = aPos[i]
bPos[i+1] = bPos[i]
if e.Op != Insert {
aPos[i+1]++
}
if e.Op != Delete {
bPos[i+1]++
}
}
hunks := []Hunk{}
i := 0
for i < len(edits) {
if edits[i].Op == Equal {
i++
continue
}
start := i - context
if start < 0 {
start = 0
}
last := i
// Extend while the next change is close enough that the context around
// the two would overlap. A longer run of equals ends the hunk.
j := i + 1
for j < len(edits) {
if edits[j].Op != Equal {
last = j
j++
continue
}
run := 0
for j+run < len(edits) && edits[j+run].Op == Equal {
run++
}
if j+run >= len(edits) || run > 2*context {
break
}
j += run
}
stop := last + context
if stop > len(edits)-1 {
stop = len(edits) - 1
}
h := Hunk{
AStart: aPos[start] + 1,
ALines: aPos[stop+1] - aPos[start],
BStart: bPos[start] + 1,
BLines: bPos[stop+1] - bPos[start],
Edits: edits[start : stop+1],
}
if h.ALines == 0 {
h.AStart = aPos[start]
}
if h.BLines == 0 {
h.BStart = bPos[start]
}
hunks = append(hunks, h)
i = stop + 1
}
return hunks
}
// Unified renders the body of a unified diff: the @@ headers and their lines,
// and nothing else. The --- and +++ file headers name files, which a realm does
// not have, so they are the caller's to add.
func Unified(a, b string, context int) string {
return UnifiedScript(Lines(a, b), context)
}
// UnifiedScript renders an already-computed script, for a caller that wants the
// counts or the Minimal flag as well as the text.
func UnifiedScript(s Script, context int) string {
var sb strings.Builder
for _, h := range Hunks(s, context) {
sb.WriteString(h.Header())
sb.WriteString("\n")
for _, e := range h.Edits {
sb.WriteString(e.Op.String())
sb.WriteString(e.Line)
sb.WriteString("\n")
}
}
return sb.String()
}
myersdiff_test.gno
package myersdiff
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
// render turns a script into one compact string per line, so a table case can
// state the whole expected script as text instead of a slice literal.
func render(s Script) string {
var sb strings.Builder
for i, e := range s.Edits {
if i > 0 {
sb.WriteString("|")
}
sb.WriteString(e.Op.String())
sb.WriteString(e.Line)
}
return sb.String()
}
func TestScript(t *testing.T) {
cases := []struct {
name string
a string
b string
want string
}{
{"identical", "a\nb\nc", "a\nb\nc", " a| b| c"},
{"both empty", "", "", ""},
{"insert into empty", "", "a\nb", "+a|+b"},
{"delete to empty", "a\nb", "", "-a|-b"},
{"append one", "a", "a\nb", " a|+b"},
{"prepend one", "b", "a\nb", "+a| b"},
{"substitute middle", "a\nb\nc", "a\nx\nc", " a|-b|+x| c"},
{"delete middle", "a\nb\nc", "a\nc", " a|-b| c"},
{"nothing in common", "a\nb", "x\ny", "-a|-b|+x|+y"},
{"trailing newline is a line", "a", "a\n", " a|+"},
{"move one line down", "a\nb\nc", "b\nc\na", "-a| b| c|+a"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := Lines(tc.a, tc.b)
uassert.True(t, got.Minimal, "expected a minimal script")
uassert.Equal(t, tc.want, render(got))
})
}
}
// TestScriptIsShortest is the property the algorithm exists for. A correct but
// lazy implementation (delete everything, insert everything) passes every
// round-trip test, so the count of changed lines is asserted separately.
func TestScriptIsShortest(t *testing.T) {
cases := []struct {
name string
a string
b string
changed int
}{
{"one substitution", "a\nb\nc", "a\nx\nc", 2},
{"one insertion", "a\nb\nc", "a\nb\nx\nc", 1},
{"one deletion", "a\nb\nc", "a\nc", 1},
{"two far apart", "a\nb\nc\nd\ne", "x\nb\nc\nd\ny", 4},
{"classic abcabba to cbabac", "a\nb\nc\na\nb\nb\na", "c\nb\na\nb\na\nc", 5},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := Lines(tc.a, tc.b)
changed := s.Added() + s.Deleted()
uassert.Equal(t, tc.changed, changed)
})
}
}
// TestApplyRoundTrips is the correctness half: whatever script comes out, it
// has to turn a back into b. Checked on the minimal path and on the budget
// fallback, because the fallback is the one nobody looks at.
func TestApplyRoundTrips(t *testing.T) {
cases := []struct {
name string
a string
b string
budget int
}{
{"typical patch", "one\ntwo\nthree\nfour", "one\n2\nthree\nfour\nfive", 0},
{"full rewrite", "a\nb\nc\nd", "w\nx\ny\nz", 0},
{"starved budget", "a\nb\nc\nd", "w\nx\ny\nz", 1},
{"empty to empty", "", "", 0},
{"repeated lines", "x\nx\nx\nx", "x\nx", 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := Budget(split(tc.a), split(tc.b), tc.budget)
lines, ok := s.Apply(split(tc.a))
uassert.True(t, ok, "the script should describe its own source")
uassert.Equal(t, tc.b, strings.Join(lines, "\n"))
})
}
}
// TestBudgetFallback pins what a starved search returns. The script stops being
// minimal and says so; it does not stop being correct and it does not panic.
func TestBudgetFallback(t *testing.T) {
a := split("a\nb\nc\nd\ne\nf")
b := split("u\nv\nw\nx\ny\nz")
starved := Budget(a, b, 2)
uassert.False(t, starved.Minimal, "a two-round budget cannot reach a 12-edit script")
uassert.Equal(t, 6, starved.Deleted())
uassert.Equal(t, 6, starved.Added())
uassert.Equal(t, 0, starved.Unchanged())
full := Budget(a, b, 0)
uassert.True(t, full.Minimal, "the default budget is enough for six lines")
applied, ok := full.Apply(a)
uassert.True(t, ok, "the minimal script should describe its own source")
uassert.Equal(t, strings.Join(b, "\n"), strings.Join(applied, "\n"))
// A budget above what the script needs changes nothing, and a budget larger
// than any possible script is not an error.
wide := Budget(a, b, 10000)
uassert.True(t, wide.Minimal, "an oversized budget still terminates")
uassert.Equal(t, render(full), render(wide))
}
func TestCounts(t *testing.T) {
s := Lines("a\nb\nc", "a\nx\ny\nc")
uassert.Equal(t, 2, s.Added())
uassert.Equal(t, 1, s.Deleted())
uassert.Equal(t, 2, s.Unchanged())
}
func TestHunks(t *testing.T) {
// Eleven lines, two changes far enough apart to stay separate at context 1
// and to merge at context 3.
a := "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11"
b := "1\n2\nX\n4\n5\n6\n7\n8\nY\n10\n11"
s := Lines(a, b)
narrow := Hunks(s, 1)
uassert.Equal(t, 2, len(narrow))
uassert.Equal(t, "@@ -2,3 +2,3 @@", narrow[0].Header())
uassert.Equal(t, "@@ -8,3 +8,3 @@", narrow[1].Header())
wide := Hunks(s, 3)
uassert.Equal(t, 1, len(wide))
uassert.Equal(t, "@@ -1,11 +1,11 @@", wide[0].Header())
none := Hunks(Lines(a, a), 3)
uassert.Equal(t, 0, len(none))
zero := Hunks(s, 0)
uassert.Equal(t, 2, len(zero))
uassert.Equal(t, "@@ -3 +3 @@", zero[0].Header())
}
// TestHunkHeaderEmptySide pins the one header convention that is not obvious:
// a side contributing no lines reports the line before the hunk and a length of
// zero, which is what diff(1) prints and what patch(1) expects to read back.
func TestHunkHeaderEmptySide(t *testing.T) {
into := Hunks(Lines("", "a\nb"), 0)
uassert.Equal(t, 1, len(into))
uassert.Equal(t, "@@ -0,0 +1,2 @@", into[0].Header())
outOf := Hunks(Lines("a\nb", ""), 0)
uassert.Equal(t, 1, len(outOf))
uassert.Equal(t, "@@ -1,2 +0,0 @@", outOf[0].Header())
negative := Hunks(Lines("a", "b"), -5)
uassert.Equal(t, 1, len(negative))
uassert.Equal(t, "@@ -1 +1 @@", negative[0].Header())
}
func TestUnified(t *testing.T) {
a := "the quick\nbrown fox\njumps over\nthe lazy dog"
b := "the quick\nred fox\njumps over\nthe lazy dog\nand runs"
want := "@@ -1,4 +1,5 @@\n the quick\n-brown fox\n+red fox\n jumps over\n the lazy dog\n+and runs\n"
uassert.Equal(t, want, Unified(a, b, 3))
uassert.Equal(t, "", Unified(a, a, 3))
uassert.Equal(t, Unified(a, b, 3), UnifiedScript(Lines(a, b), 3))
}
func TestOpString(t *testing.T) {
uassert.Equal(t, "-", Delete.String())
uassert.Equal(t, " ", Equal.String())
uassert.Equal(t, "+", Insert.String())
}
func TestMaxLines(cur realm, t *testing.T) {
big := make([]string, MaxLines+1)
ok := make([]string, MaxLines)
uassert.PanicsWithMessage(t, cur, "myersdiff: input exceeds MaxLines", func() { Budget(big, ok, 0) })
uassert.PanicsWithMessage(t, cur, "myersdiff: input exceeds MaxLines", func() { Budget(ok, big, 0) })
// MaxLines identical lines is the cheap case: d is zero, so the search ends
// in the first round whatever the size.
uassert.NotPanics(t, cur, func() { Budget(ok, ok, 0) })
}
// TestApplyChecksTheSourceIsWhatTheScriptDescribes closes the gap a review
// found on the first pass: Apply used to ignore its argument entirely, so it
// replayed any script into the script's own right-hand side and reported
// nothing. The round trip then proved only that the script agreed with itself,
// and the demo's applies() check was vacuous for the same reason.
func TestApplyChecksTheSourceIsWhatTheScriptDescribes(t *testing.T) {
s := Lines("a\nb\nc", "a\nx\nc")
got, ok := s.Apply([]string{"a", "b", "c"})
uassert.True(t, ok, "the script's own source should be accepted")
uassert.Equal(t, "a\nx\nc", strings.Join(got, "\n"))
_, ok = s.Apply([]string{"q", "b", "c"})
uassert.False(t, ok, "an Equal line absent from the source is not a script for it")
_, ok = s.Apply([]string{"a", "q", "c"})
uassert.False(t, ok, "a Delete line absent from the source is not a script for it")
_, ok = s.Apply([]string{"a", "b"})
uassert.False(t, ok, "a source shorter than the script consumes")
_, ok = s.Apply([]string{"a", "b", "c", "d"})
uassert.False(t, ok, "a source with a line the script never consumed")
_, ok = s.Apply([]string{})
uassert.False(t, ok, "an empty source against a three-line script")
}
// TestLinesEnforcesTheLineCap covers the other half of the same review:
// MaxLines guarded the comparison but not the strings.Split in front of it, so
// a caller could force an arbitrarily large line slice and only then be
// refused. Nothing here distinguishes the two orders, because the difference is
// an allocation and gno test cannot observe one. What it does pin is that Lines
// and Unified enforce the cap at all, which nothing asserted before.
func TestLinesEnforcesTheLineCap(cur realm, t *testing.T) {
over := strings.Repeat("x\n", MaxLines)
atCap := strings.Repeat("x\n", MaxLines-1) + "x"
uassert.PanicsWithMessage(t, cur, "myersdiff: input exceeds MaxLines", func() { Lines(over, "") })
uassert.PanicsWithMessage(t, cur, "myersdiff: input exceeds MaxLines", func() { Lines("", over) })
uassert.PanicsWithMessage(t, cur, "myersdiff: input exceeds MaxLines", func() { Unified("", over, 1) })
uassert.NotPanics(t, cur, func() { Lines(atCap, atCap) })
}
// TestEffectiveRounds pins the one number that decides how much memory the
// search can be made to allocate. The frontier is snapshotted once per round,
// so the round count is the memory bound, and before MaxBudget existed a caller
// could ask for 8,192 rounds by passing a large budget with two MaxLines
// documents. This is asserted directly rather than through a diff, because the
// inputs that would show it behaviourally take minutes to run.
func TestEffectiveRounds(t *testing.T) {
cases := []struct {
name string
budget int
n, m int
want int
}{
{"default applies when unset", 0, 1000, 1000, DefaultBudget},
{"default applies when negative", -7, 1000, 1000, DefaultBudget},
{"a small budget is kept", 5, 100, 100, 5},
{"no script is longer than n+m", 0, 10, 10, 20},
{"a large budget is capped at MaxBudget", 100000, MaxLines, MaxLines, MaxBudget},
{"MaxBudget never exceeds n+m either", 100000, 3, 4, 7},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
uassert.Equal(t, tc.want, effectiveRounds(tc.budget, tc.n, tc.m))
})
}
uassert.True(t, MaxBudget >= DefaultBudget, "the cap must leave the default reachable")
}