Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

5 Commits

Repository files navigation

diff

Go Reference

This package provides a generic implementation of the Myers diff algorithm that produces sequential edits.

Usage

To produce a list of edits, you can create an edit type and build a slice using a callback provided to the Diff method.

import"github.com/buth/diff"typeedit[Tcomparable] struct {
start, end diff.Positionreplacement []T
}
funclistOfEdits[Tcomparable](dst, src []T) []edit[T] {
varedits []edit[T]
diff.Diff(dst, src, nil, func(start, end diff.Position, replacement []T) {
edits=append(edits, edit[T]{
start: start,
end: end,
replacement: replacement
})
})
returnedits
} 

Keep in mind that the provided replacement slice will be a subslice of the destination value if it is not nil.

To apply the edits, you can iterate through the resulting list using an index of the source slice as the starting point.

funcapplyEdits[Tcomparable](src []T, edits []edit[T]) []T {
dst:=make([]T, 0, len(src))
i:=0for_, edit:=rangeedits {
dst=append(dst, src[i:edit.start.Index]...)
dst=append(dst, edit.replacement...)
i=edit.end.Index
}
returnappend(dst, src[i:]...)
}

About

A generic diff implementation that produces sequential edits.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Used by

Contributors

Languages