diff

package module
v0.0.0-...-a50a595 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2023 License: Apache-2.0 Imports: 0 Imported by: 0

README

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"

type edit[T comparable] struct {
	start, end  diff.Position
	replacement []T
}

func listOfEdits[T comparable](dst, src []T) []edit[T] {
	var edits []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
		})
	})

	return edits
} 

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.

func applyEdits[T comparable](src []T, edits []edit[T]) []T {
	dst := make([]T, 0, len(src))

	i := 0
	for _, edit := range edits {
		dst = append(dst, src[i:edit.start.Index]...)
		dst = append(dst, edit.replacement...)
		i = edit.end.Index
	}

	return append(dst, src[i:]...)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Diff

func Diff[T comparable](a, b []T, isNewline func(T) bool, edit func(start, end Position, replacement []T))

Diff will call edit in order for each edit of b required to produce a. Start and end locations are relative to the begining of b, and the replacement slice will either be nil or a subslice of a.

Types

type Position

type Position struct {
	Index  int
	Line   int
	Column int
}

Position represents a point in the source input.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL