github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/internal/diff/diff.go (about) 1 // Copyright 2022 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package diff 6 7 // Diff returns an anchored diff of the two texts old and new 8 // in the “unified diff” format. If old and new are identical, 9 // Diff returns a nil slice (no output). 10 // 11 // Unix diff implementations typically look for a diff with 12 // the smallest number of lines inserted and removed, 13 // which can in the worst case take time quadratic in the 14 // number of lines in the texts. As a result, many implementations 15 // either can be made to run for a long time or cut off the search 16 // after a predetermined amount of work. 17 // 18 // In contrast, this implementation looks for a diff with the 19 // smallest number of “unique” lines inserted and removed, 20 // where unique means a line that appears just once in both old and new. 21 // We call this an “anchored diff” because the unique lines anchor 22 // the chosen matching regions. An anchored diff is usually clearer 23 // than a standard diff, because the algorithm does not try to 24 // reuse unrelated blank lines or closing braces. 25 // The algorithm also guarantees to run in O(n log n) time 26 // instead of the standard O(n²) time. 27 // 28 // Some systems call this approach a “patience diff,” named for 29 // the “patience sorting” algorithm, itself named for a solitaire card game. 30 // We avoid that name for two reasons. First, the name has been used 31 // for a few different variants of the algorithm, so it is imprecise. 32 // Second, the name is frequently interpreted as meaning that you have 33 // to wait longer (to be patient) for the diff, meaning that it is a slower algorithm, 34 // when in fact the algorithm is faster than the standard one. 35 func Diff(oldName string, old []byte, newName string, new []byte) []byte