// Copyright (c) 2012-2016 The go-diff authors. All rights reserved.// https://github.com/sergi/go-diff// See the included LICENSE file for license details.//// go-diff is a Go implementation of Google's Diff, Match, and Patch library// Original library is Copyright (c) 2006 Google Inc.// http://code.google.com/p/google-diff-match-patch/package diffmatchpatchimport ()// Operation defines the operation of a diff item.typeOperationint8//go:generate stringer -type=Operation -trimprefix=Diffconst (// DiffDelete item represents a delete diff.DiffDeleteOperation = -1// DiffInsert item represents an insert diff.DiffInsertOperation = 1// DiffEqual item represents an equal diff.DiffEqualOperation = 0)// Diff represents one diff operationtypeDiffstruct { Type Operation Text string}// splice removes amount elements from slice at index index, replacing them with elements.func splice( []Diff, int, int, ...Diff) []Diff {iflen() == {// Easy case: overwrite the relevant items.copy([:], )return }iflen() < {// Fewer new items than old. // Copy in the new items.copy([:], )// Shift the remaining items left.copy([+len():], [+:])// Calculate the new end of the slice. := len() - + len()// Zero stranded elements at end so that they can be garbage collected. := [:]for := range { [] = Diff{} }return [:] }// More new items than old. // Make room in slice for new elements. // There's probably an even more efficient way to do this, // but this is simple and clear. := len() - + len()forlen() < { = append(, Diff{}) }// Shift slice elements right to make room for new elements.copy([+len():], [+:])// Copy in new elements.copy([:], )return}// DiffMain finds the differences between two texts.// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.func ( *DiffMatchPatch) (, string, bool) []Diff {return .DiffMainRunes([]rune(), []rune(), )}// DiffMainRunes finds the differences between two rune sequences.// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.func ( *DiffMatchPatch) (, []rune, bool) []Diff {vartime.Timeif .DiffTimeout > 0 { = time.Now().Add(.DiffTimeout) }return .diffMainRunes(, , , )}func ( *DiffMatchPatch) (, []rune, bool, time.Time) []Diff {ifrunesEqual(, ) {var []Diffiflen() > 0 { = append(, Diff{DiffEqual, string()}) }return }// Trim off common prefix (speedup). := commonPrefixLength(, ) := [:] = [:] = [:]// Trim off common suffix (speedup). = commonSuffixLength(, ) := [len()-:] = [:len()-] = [:len()-]// Compute the diff on the middle block. := .diffCompute(, , , )// Restore the prefix and suffix.iflen() != 0 { = append([]Diff{{DiffEqual, string()}}, ...) }iflen() != 0 { = append(, Diff{DiffEqual, string()}) }return .DiffCleanupMerge()}// diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix.func ( *DiffMatchPatch) (, []rune, bool, time.Time) []Diff { := []Diff{}iflen() == 0 {// Just add some text (speedup).returnappend(, Diff{DiffInsert, string()}) } elseiflen() == 0 {// Just delete some text (speedup).returnappend(, Diff{DiffDelete, string()}) }var , []runeiflen() > len() { = = } else { = = }if := runesIndex(, ); != -1 { := DiffInsert// Swap insertions for deletions if diff is reversed.iflen() > len() { = DiffDelete }// Shorter text is inside the longer text (speedup).return []Diff{Diff{, string([:])},Diff{DiffEqual, string()},Diff{, string([+len():])}, } } elseiflen() == 1 {// Single character string. // After the previous speedup, the character can't be an equality.return []Diff{ {DiffDelete, string()}, {DiffInsert, string()}, }// Check to see if the problem can be split in two. } elseif := .diffHalfMatch(, ); != nil {// A half-match was found, sort out the return data. := [0] := [1] := [2] := [3] := [4]// Send both pairs off for separate processing. := .diffMainRunes(, , , ) := .diffMainRunes(, , , )// Merge the results. := = append(, Diff{DiffEqual, string()}) = append(, ...)return } elseif && len() > 100 && len() > 100 {return .diffLineMode(, , ) }return .diffBisect(, , )}// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs.func ( *DiffMatchPatch) (, []rune, time.Time) []Diff {// Scan the text on a line-by-line basis first. , , := .DiffLinesToRunes(string(), string()) := .diffMainRunes(, , false, )// Convert the diff back to original text. = .DiffCharsToLines(, )// Eliminate freak matches (e.g. blank lines) = .DiffCleanupSemantic()// Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. = append(, Diff{DiffEqual, ""}) := 0 := 0 := 0// NOTE: Rune slices are slower than using strings in this case. := "" := ""for < len() {switch [].Type {caseDiffInsert: ++ += [].TextcaseDiffDelete: ++ += [].TextcaseDiffEqual:// Upon reaching an equality, check for prior redundancies.if >= 1 && >= 1 {// Delete the offending records and add the merged ones. = splice(, --, +) = - - := .diffMainRunes([]rune(), []rune(), false, )for := len() - 1; >= 0; -- { = splice(, , 0, []) } = + len() } = 0 = 0 = "" = "" } ++ }return [:len()-1] // Remove the dummy entry at the end.}// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff.// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character.// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.func ( *DiffMatchPatch) (, string, time.Time) []Diff {// Unused in this code, but retained for interface compatibility.return .diffBisect([]rune(), []rune(), )}// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff.// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations.func ( *DiffMatchPatch) (, []rune, time.Time) []Diff {// Cache the text lengths to prevent multiple calls. , := len(), len() := ( + + 1) / 2 := := 2 * := make([]int, ) := make([]int, )for := range { [] = -1 [] = -1 } [+1] = 0 [+1] = 0 := - // If the total number of characters is odd, then the front path will collide with the reverse path. := (%2 != 0)// Offsets for start and end of k loop. Prevents mapping of space beyond the grid. := 0 := 0 := 0 := 0for := 0; < ; ++ {// Bail out if deadline is reached.if !.IsZero() && %16 == 0 && time.Now().After() {break }// Walk the front path one step.for := - + ; <= -; += 2 { := + varintif == - || ( != && [-1] < [+1]) { = [+1] } else { = [-1] + 1 } := - for < && < {if [] != [] {break } ++ ++ } [] = if > {// Ran off the right of the graph. += 2 } elseif > {// Ran off the bottom of the graph. += 2 } elseif { := + - if >= 0 && < && [] != -1 {// Mirror x2 onto top-left coordinate system. := - []if >= {// Overlap detected.return .diffBisectSplit(, , , , ) } } } }// Walk the reverse path one step.for := - + ; <= -; += 2 { := + varintif == - || ( != && [-1] < [+1]) { = [+1] } else { = [-1] + 1 }var = - for < && < {if [--1] != [--1] {break } ++ ++ } [] = if > {// Ran off the left of the graph. += 2 } elseif > {// Ran off the top of the graph. += 2 } elseif ! { := + - if >= 0 && < && [] != -1 { := [] := + - // Mirror x2 onto top-left coordinate system. = - if >= {// Overlap detected.return .diffBisectSplit(, , , , ) } } } } }// Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all.return []Diff{ {DiffDelete, string()}, {DiffInsert, string()}, }}func ( *DiffMatchPatch) (, []rune, , int,time.Time) []Diff { := [:] := [:] := [:] := [:]// Compute both diffs serially. := .diffMainRunes(, , false, ) := .diffMainRunes(, , false, )returnappend(, ...)}// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line.// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes.func ( *DiffMatchPatch) (, string) (string, string, []string) { , , := .diffLinesToStrings(, )return , , }// DiffLinesToRunes splits two texts into a list of runes.func ( *DiffMatchPatch) (, string) ([]rune, []rune, []string) { , , := .diffLinesToStrings(, )return []rune(), []rune(), }// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text.func ( *DiffMatchPatch) ( []Diff, []string) []Diff { := make([]Diff, 0, len())for , := range { := []rune(.Text) := make([]string, len())for , := range { [] = [runeToInt()] } .Text = strings.Join(, "") = append(, ) }return}// DiffCommonPrefix determines the common prefix length of two strings.func ( *DiffMatchPatch) (, string) int {// Unused in this code, but retained for interface compatibility.returncommonPrefixLength([]rune(), []rune())}// DiffCommonSuffix determines the common suffix length of two strings.func ( *DiffMatchPatch) (, string) int {// Unused in this code, but retained for interface compatibility.returncommonSuffixLength([]rune(), []rune())}// commonPrefixLength returns the length of the common prefix of two rune slices.func commonPrefixLength(, []rune) int {// Linear search. See comment in commonSuffixLength. := 0for ; < len() && < len(); ++ {if [] != [] {return } }return}// commonSuffixLength returns the length of the common suffix of two rune slices.func commonSuffixLength(, []rune) int {// Use linear search rather than the binary search discussed at https://neil.fraser.name/news/2007/10/09/. // See discussion at https://github.com/sergi/go-diff/issues/54. := len() := len()for := 0; ; ++ { -- --if < 0 || < 0 || [] != [] {return } }}// DiffCommonOverlap determines if the suffix of one string is the prefix of another.func ( *DiffMatchPatch) ( string, string) int {// Cache the text lengths to prevent multiple calls. := len() := len()// Eliminate the null case.if == 0 || == 0 {return0 }// Truncate the longer string.if > { = [-:] } elseif < { = [0:] } := int(math.Min(float64(), float64()))// Quick check for the worst case.if == {return }// Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/ := 0 := 1for { := [-:] := strings.Index(, )if == -1 {break } += if == 0 || [-:] == [0:] { = ++ } }return}// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs.func ( *DiffMatchPatch) (, string) []string {// Unused in this code, but retained for interface compatibility. := .diffHalfMatch([]rune(), []rune())if == nil {returnnil } := make([]string, len())for , := range { [] = string() }return}func ( *DiffMatchPatch) (, []rune) [][]rune {if .DiffTimeout <= 0 {// Don't risk returning a non-optimal diff if we have unlimited time.returnnil }var , []runeiflen() > len() { = = } else { = = }iflen() < 4 || len()*2 < len() {returnnil// Pointless. }// First check if the second quarter is the seed for a half-match. := .diffHalfMatchI(, , int(float64(len()+3)/4))// Check again based on the third quarter. := .diffHalfMatchI(, , int(float64(len()+1)/2)) := [][]rune{}if == nil && == nil {returnnil } elseif == nil { = } elseif == nil { = } else {// Both matched. Select the longest.iflen([4]) > len([4]) { = } else { = } }// A half-match was found, sort out the return data.iflen() > len() {return }return [][]rune{[2], [3], [0], [1], [4]}}// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext?// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match.func ( *DiffMatchPatch) (, []rune, int) [][]rune {var []runevar []runevarintvar []runevar []runevar []runevar []rune// Start with a 1/4 length substring at position i as a seed. := [ : +len()/4]for := runesIndexOf(, , 0); != -1; = runesIndexOf(, , +1) { := commonPrefixLength([:], [:]) := commonSuffixLength([:], [:])if < + { = [- : ] = [ : +] = len() + len() = [:-] = [+:] = [:-] = [+:] } }if *2 < len() {returnnil }return [][]rune{ , , , ,append(, ...), }}// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities.func ( *DiffMatchPatch) ( []Diff) []Diff { := false// Stack of indices where equalities are found. := make([]int, 0, len())varstring// Always equal to diffs[equalities[equalitiesLength - 1]][1]varint// Index of current position.// Number of characters that changed prior to the equality.var , int// Number of characters that changed after the equality.var , intfor < len() {if [].Type == DiffEqual {// Equality found. = append(, ) = = = 0 = 0 = [].Text } else {// An insertion or deletion.if [].Type == DiffInsert { += utf8.RuneCountInString([].Text) } else { += utf8.RuneCountInString([].Text) }// Eliminate an equality that is smaller or equal to the edits on both sides of it. := int(math.Max(float64(), float64())) := int(math.Max(float64(), float64()))ifutf8.RuneCountInString() > 0 && (utf8.RuneCountInString() <= ) && (utf8.RuneCountInString() <= ) {// Duplicate record. := [len()-1] = splice(, , 0, Diff{DiffDelete, })// Change second copy to insert. [+1].Type = DiffInsert// Throw away the equality we just deleted. = [:len()-1]iflen() > 0 { = [:len()-1] } = -1iflen() > 0 { = [len()-1] } = 0// Reset the counters. = 0 = 0 = 0 = "" = true } } ++ }// Normalize the diff.if { = .DiffCleanupMerge() } = .DiffCleanupSemanticLossless()// Find any overlaps between deletions and insertions. // e.g: <del>abcxxx</del><ins>xxxdef</ins> // -> <del>abc</del>xxx<ins>def</ins> // e.g: <del>xxxabc</del><ins>defxxx</ins> // -> <ins>def</ins>xxx<del>abc</del> // Only extract an overlap if it is as big as the edit ahead or behind it. = 1for < len() {if [-1].Type == DiffDelete && [].Type == DiffInsert { := [-1].Text := [].Text := .DiffCommonOverlap(, ) := .DiffCommonOverlap(, )if >= {iffloat64() >= float64(utf8.RuneCountInString())/2 ||float64() >= float64(utf8.RuneCountInString())/2 {// Overlap found. Insert an equality and trim the surrounding edits. = splice(, , 0, Diff{DiffEqual, [:]}) [-1].Text = [0 : len()-] [+1].Text = [:] ++ } } else {iffloat64() >= float64(utf8.RuneCountInString())/2 ||float64() >= float64(utf8.RuneCountInString())/2 {// Reverse overlap found. Insert an equality and swap and trim the surrounding edits. := Diff{DiffEqual, [:]} = splice(, , 0, ) [-1].Type = DiffInsert [-1].Text = [0 : len()-] [+1].Type = DiffDelete [+1].Text = [:] ++ } } ++ } ++ }return}// Define some regex patterns for matching boundaries.var ( nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`) whitespaceRegex = regexp.MustCompile(`\s`) linebreakRegex = regexp.MustCompile(`[\r\n]`) blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`) blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`))// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries.// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables.func diffCleanupSemanticScore(, string) int {iflen() == 0 || len() == 0 {// Edges are the best.return6 }// Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity. , := utf8.DecodeLastRuneInString() , := utf8.DecodeRuneInString() := string() := string() := nonAlphaNumericRegex.MatchString() := nonAlphaNumericRegex.MatchString() := && whitespaceRegex.MatchString() := && whitespaceRegex.MatchString() := && linebreakRegex.MatchString() := && linebreakRegex.MatchString() := && blanklineEndRegex.MatchString() := && blanklineEndRegex.MatchString()if || {// Five points for blank lines.return5 } elseif || {// Four points for line breaks.return4 } elseif && ! && {// Three points for end of sentences.return3 } elseif || {// Two points for whitespace.return2 } elseif || {// One point for non-alphanumeric.return1 }return0}// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary.// E.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.func ( *DiffMatchPatch) ( []Diff) []Diff { := 1// Intentionally ignore the first and last element (don't need checking).for < len()-1 {if [-1].Type == DiffEqual && [+1].Type == DiffEqual {// This is a single edit surrounded by equalities. := [-1].Text := [].Text := [+1].Text// First, shift the edit as far left as possible. := .DiffCommonSuffix(, )if > 0 { := [len()-:] = [0 : len()-] = + [:len()-] = + }// Second, step character by character right, looking for the best fit. := := := := diffCleanupSemanticScore(, ) +diffCleanupSemanticScore(, )forlen() != 0 && len() != 0 { , := utf8.DecodeRuneInString()iflen() < || [:] != [:] {break } += [:] = [:] + [:] = [:] := diffCleanupSemanticScore(, ) +diffCleanupSemanticScore(, )// The >= encourages trailing rather than leading whitespace on edits.if >= { = = = = } }if [-1].Text != {// We have an improvement, save it back to the diff.iflen() != 0 { [-1].Text = } else { = splice(, -1, 1) -- } [].Text = iflen() != 0 { [+1].Text = } else { = append([:+1], [+2:]...) -- } } } ++ }return}// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities.func ( *DiffMatchPatch) ( []Diff) []Diff { := false// Stack of indices where equalities are found.typestruct {int * }var *// Always equal to equalities[equalitiesLength-1][1] := "" := 0// Index of current position.// Is there an insertion operation before the last equality. := false// Is there a deletion operation before the last equality. := false// Is there an insertion operation after the last equality. := false// Is there a deletion operation after the last equality. := falsefor < len() {if [].Type == DiffEqual { // Equality found.iflen([].Text) < .DiffEditCost && ( || ) {// Candidate found. = &{ : , : , } = = = [].Text } else {// Not a candidate, and can never become one. = nil = "" } = false = false } else { // An insertion or deletion.if [].Type == DiffDelete { = true } else { = true }// Five types to be split: // <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del> // <ins>A</ins>X<ins>C</ins><del>D</del> // <ins>A</ins><del>B</del>X<ins>C</ins> // <ins>A</del>X<ins>C</ins><del>D</del> // <ins>A</ins><del>B</del>X<del>C</del>varintif { ++ }if { ++ }if { ++ }if { ++ }iflen() > 0 && (( && && && ) || ((len() < .DiffEditCost/2) && == 3)) { := .// Duplicate record. = splice(, , 0, Diff{DiffDelete, })// Change second copy to insert. [+1].Type = DiffInsert// Throw away the equality we just deleted. = . = ""if && {// No changes made which could affect previous entry, keep going. = true = true = nil } else {if != nil { = . }if != nil { = . } else { = -1 } = false = false } = true } } ++ }if { = .DiffCleanupMerge() }return}// DiffCleanupMerge reorders and merges like edit sections. Merge equalities.// Any edit section can move as long as it doesn't cross an equality.func ( *DiffMatchPatch) ( []Diff) []Diff {// Add a dummy entry at the end. = append(, Diff{DiffEqual, ""}) := 0 := 0 := 0 := 0 := []rune(nil) := []rune(nil)for < len() {switch [].Type {caseDiffInsert: ++ = append(, []rune([].Text)...) ++breakcaseDiffDelete: ++ = append(, []rune([].Text)...) ++breakcaseDiffEqual:// Upon reaching an equality, check for prior redundancies.if + > 1 {if != 0 && != 0 {// Factor out any common prefixies. = commonPrefixLength(, )if != 0 { := - - if > 0 && [-1].Type == DiffEqual { [-1].Text += string([:]) } else { = append([]Diff{{DiffEqual, string([:])}}, ...) ++ } = [:] = [:] }// Factor out any common suffixies. = commonSuffixLength(, )if != 0 { := len() - := len() - [].Text = string([:]) + [].Text = [:] = [:] } }// Delete the offending records and add the merged ones.if == 0 { = splice(, -, +,Diff{DiffInsert, string()}) } elseif == 0 { = splice(, -, +,Diff{DiffDelete, string()}) } else { = splice(, --, +,Diff{DiffDelete, string()},Diff{DiffInsert, string()}) } = - - + 1if != 0 { ++ }if != 0 { ++ } } elseif != 0 && [-1].Type == DiffEqual {// Merge this equality with the previous one. [-1].Text += [].Text = append([:], [+1:]...) } else { ++ } = 0 = 0 = nil = nilbreak } }iflen([len()-1].Text) == 0 { = [0 : len()-1] // Remove the dummy entry at the end. }// Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: A<ins>BA</ins>C -> <ins>AB</ins>AC := false = 1// Intentionally ignore the first and last element (don't need checking).for < (len() - 1) {if [-1].Type == DiffEqual && [+1].Type == DiffEqual {// This is a single edit surrounded by equalities.ifstrings.HasSuffix([].Text, [-1].Text) {// Shift the edit over the previous equality. [].Text = [-1].Text + [].Text[:len([].Text)-len([-1].Text)] [+1].Text = [-1].Text + [+1].Text = splice(, -1, 1) = true } elseifstrings.HasPrefix([].Text, [+1].Text) {// Shift the edit over the next equality. [-1].Text += [+1].Text [].Text = [].Text[len([+1].Text):] + [+1].Text = splice(, +1, 1) = true } } ++ }// If shifts were made, the diff needs reordering and another shift sweep.if { = .() }return}// DiffXIndex returns the equivalent location in s2.func ( *DiffMatchPatch) ( []Diff, int) int { := 0 := 0 := 0 := 0 := Diff{}for := 0; < len(); ++ { := []if .Type != DiffInsert {// Equality or deletion. += len(.Text) }if .Type != DiffDelete {// Equality or insertion. += len(.Text) }if > {// Overshot the location. = break } = = }if .Type == DiffDelete {// The location was deleted.return }// Add the remaining character length.return + ( - )}// DiffPrettyHtml converts a []Diff into a pretty HTML report.// It is intended as an example from which to write one's own display functions.func ( *DiffMatchPatch) ( []Diff) string {varbytes.Bufferfor , := range { := strings.Replace(html.EscapeString(.Text), "\n", "¶<br>", -1)switch .Type {caseDiffInsert: _, _ = .WriteString("<ins style=\"background:#e6ffe6;\">") _, _ = .WriteString() _, _ = .WriteString("</ins>")caseDiffDelete: _, _ = .WriteString("<del style=\"background:#ffe6e6;\">") _, _ = .WriteString() _, _ = .WriteString("</del>")caseDiffEqual: _, _ = .WriteString("<span>") _, _ = .WriteString() _, _ = .WriteString("</span>") } }return .String()}// DiffPrettyText converts a []Diff into a colored text report.func ( *DiffMatchPatch) ( []Diff) string {varbytes.Bufferfor , := range { := .Textswitch .Type {caseDiffInsert: := strings.Split(, "\n")for , := range { _, _ = .WriteString("\x1b[32m") _, _ = .WriteString()if < len()-1 { _, _ = .WriteString("\x1b[0m\n") } else { _, _ = .WriteString("\x1b[0m") } }caseDiffDelete: := strings.Split(, "\n")for , := range { _, _ = .WriteString("\x1b[31m") _, _ = .WriteString()if < len()-1 { _, _ = .WriteString("\x1b[0m\n") } else { _, _ = .WriteString("\x1b[0m") } }caseDiffEqual: _, _ = .WriteString() } }return .String()}// DiffText1 computes and returns the source text (all equalities and deletions).func ( *DiffMatchPatch) ( []Diff) string {//StringBuilder text = new StringBuilder()varbytes.Bufferfor , := range {if .Type != DiffInsert { _, _ = .WriteString(.Text) } }return .String()}// DiffText2 computes and returns the destination text (all equalities and insertions).func ( *DiffMatchPatch) ( []Diff) string {varbytes.Bufferfor , := range {if .Type != DiffDelete { _, _ = .WriteString(.Text) } }return .String()}// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters.func ( *DiffMatchPatch) ( []Diff) int { := 0 := 0 := 0for , := range {switch .Type {caseDiffInsert: += utf8.RuneCountInString(.Text)caseDiffDelete: += utf8.RuneCountInString(.Text)caseDiffEqual:// A deletion and an insertion is one substitution. += max(, ) = 0 = 0 } } += max(, )return}// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2.// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation.func ( *DiffMatchPatch) ( []Diff) string {varbytes.Bufferfor , := range {switch .Type {caseDiffInsert: _, _ = .WriteString("+") _, _ = .WriteString(strings.Replace(url.QueryEscape(.Text), "+", " ", -1)) _, _ = .WriteString("\t")breakcaseDiffDelete: _, _ = .WriteString("-") _, _ = .WriteString(strconv.Itoa(utf8.RuneCountInString(.Text))) _, _ = .WriteString("\t")breakcaseDiffEqual: _, _ = .WriteString("=") _, _ = .WriteString(strconv.Itoa(utf8.RuneCountInString(.Text))) _, _ = .WriteString("\t")break } } := .String()iflen() != 0 {// Strip off trailing tab character. = [0 : utf8.RuneCountInString()-1] = unescaper.Replace() }return}// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff.func ( *DiffMatchPatch) ( string, string) ( []Diff, error) { := 0 := []rune()for , := rangestrings.Split(, "\t") {iflen() == 0 {// Blank tokens are ok (from a trailing \t).continue }// Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality). := [1:]switch := [0]; {case'+':// Decode would Diff all "+" to " " = strings.Replace(, "+", "%2b", -1) , = url.QueryUnescape()if != nil {returnnil, }if !utf8.ValidString() {returnnil, fmt.Errorf("invalid UTF-8 token: %q", ) } = append(, Diff{DiffInsert, })case'=', '-': , := strconv.ParseInt(, 10, 0)if != nil {returnnil, } elseif < 0 {returnnil, errors.New("Negative number in DiffFromDelta: " + ) } += int()// Break out if we are out of bounds, go1.6 can't handle this very wellif > len() {break }// Remember that string slicing is by byte - we want by rune here. := string([-int() : ])if == '=' { = append(, Diff{DiffEqual, }) } else { = append(, Diff{DiffDelete, }) }default:// Anything else is an error.returnnil, errors.New("Invalid diff operation in DiffFromDelta: " + string([0])) } }if != len() {returnnil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", , len()) }return , nil}// diffLinesToStrings splits two texts into a list of strings. Each string represents one line.func ( *DiffMatchPatch) (, string) (string, string, []string) { := []string{""} // e.g. lineArray[4] == 'Hello\n' := make(map[string]int)//Each string has the index of lineArray which it points to := .diffLinesToStringsMunge(, &, ) := .diffLinesToStringsMunge(, &, )returnintArrayToString(), intArrayToString(), }// diffLinesToStringsMunge splits a text into an array of strings, and reduces the texts to a []index.func ( *DiffMatchPatch) ( string, *[]string, map[string]int) []index { := 0 := -1 := []index{}for < len()-1 { = indexOf(, "\n", )if == -1 { = len() - 1 } := [ : +1] = + 1 , := []if { = append(, index()) } else { * = append(*, ) [] = len(*) - 1 = append(, index(len(*)-1)) } }return}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.