report_slices.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. // Copyright 2019, 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. package cmp
  5. import (
  6. "bytes"
  7. "fmt"
  8. "math"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "unicode"
  13. "unicode/utf8"
  14. "github.com/google/go-cmp/cmp/internal/diff"
  15. )
  16. // CanFormatDiffSlice reports whether we support custom formatting for nodes
  17. // that are slices of primitive kinds or strings.
  18. func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool {
  19. switch {
  20. case opts.DiffMode != diffUnknown:
  21. return false // Must be formatting in diff mode
  22. case v.NumDiff == 0:
  23. return false // No differences detected
  24. case !v.ValueX.IsValid() || !v.ValueY.IsValid():
  25. return false // Both values must be valid
  26. case v.NumIgnored > 0:
  27. return false // Some ignore option was used
  28. case v.NumTransformed > 0:
  29. return false // Some transform option was used
  30. case v.NumCompared > 1:
  31. return false // More than one comparison was used
  32. case v.NumCompared == 1 && v.Type.Name() != "":
  33. // The need for cmp to check applicability of options on every element
  34. // in a slice is a significant performance detriment for large []byte.
  35. // The workaround is to specify Comparer(bytes.Equal),
  36. // which enables cmp to compare []byte more efficiently.
  37. // If they differ, we still want to provide batched diffing.
  38. // The logic disallows named types since they tend to have their own
  39. // String method, with nicer formatting than what this provides.
  40. return false
  41. }
  42. // Check whether this is an interface with the same concrete types.
  43. t := v.Type
  44. vx, vy := v.ValueX, v.ValueY
  45. if t.Kind() == reflect.Interface && !vx.IsNil() && !vy.IsNil() && vx.Elem().Type() == vy.Elem().Type() {
  46. vx, vy = vx.Elem(), vy.Elem()
  47. t = vx.Type()
  48. }
  49. // Check whether we provide specialized diffing for this type.
  50. switch t.Kind() {
  51. case reflect.String:
  52. case reflect.Array, reflect.Slice:
  53. // Only slices of primitive types have specialized handling.
  54. switch t.Elem().Kind() {
  55. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  56. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
  57. reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
  58. default:
  59. return false
  60. }
  61. // Both slice values have to be non-empty.
  62. if t.Kind() == reflect.Slice && (vx.Len() == 0 || vy.Len() == 0) {
  63. return false
  64. }
  65. // If a sufficient number of elements already differ,
  66. // use specialized formatting even if length requirement is not met.
  67. if v.NumDiff > v.NumSame {
  68. return true
  69. }
  70. default:
  71. return false
  72. }
  73. // Use specialized string diffing for longer slices or strings.
  74. const minLength = 64
  75. return vx.Len() >= minLength && vy.Len() >= minLength
  76. }
  77. // FormatDiffSlice prints a diff for the slices (or strings) represented by v.
  78. // This provides custom-tailored logic to make printing of differences in
  79. // textual strings and slices of primitive kinds more readable.
  80. func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode {
  81. assert(opts.DiffMode == diffUnknown)
  82. t, vx, vy := v.Type, v.ValueX, v.ValueY
  83. if t.Kind() == reflect.Interface {
  84. vx, vy = vx.Elem(), vy.Elem()
  85. t = vx.Type()
  86. opts = opts.WithTypeMode(emitType)
  87. }
  88. // Auto-detect the type of the data.
  89. var sx, sy string
  90. var ssx, ssy []string
  91. var isString, isMostlyText, isPureLinedText, isBinary bool
  92. switch {
  93. case t.Kind() == reflect.String:
  94. sx, sy = vx.String(), vy.String()
  95. isString = true
  96. case t.Kind() == reflect.Slice && t.Elem() == reflect.TypeOf(byte(0)):
  97. sx, sy = string(vx.Bytes()), string(vy.Bytes())
  98. isString = true
  99. case t.Kind() == reflect.Array:
  100. // Arrays need to be addressable for slice operations to work.
  101. vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem()
  102. vx2.Set(vx)
  103. vy2.Set(vy)
  104. vx, vy = vx2, vy2
  105. }
  106. if isString {
  107. var numTotalRunes, numValidRunes, numLines, lastLineIdx, maxLineLen int
  108. for i, r := range sx + sy {
  109. numTotalRunes++
  110. if (unicode.IsPrint(r) || unicode.IsSpace(r)) && r != utf8.RuneError {
  111. numValidRunes++
  112. }
  113. if r == '\n' {
  114. if maxLineLen < i-lastLineIdx {
  115. maxLineLen = i - lastLineIdx
  116. }
  117. lastLineIdx = i + 1
  118. numLines++
  119. }
  120. }
  121. isPureText := numValidRunes == numTotalRunes
  122. isMostlyText = float64(numValidRunes) > math.Floor(0.90*float64(numTotalRunes))
  123. isPureLinedText = isPureText && numLines >= 4 && maxLineLen <= 1024
  124. isBinary = !isMostlyText
  125. // Avoid diffing by lines if it produces a significantly more complex
  126. // edit script than diffing by bytes.
  127. if isPureLinedText {
  128. ssx = strings.Split(sx, "\n")
  129. ssy = strings.Split(sy, "\n")
  130. esLines := diff.Difference(len(ssx), len(ssy), func(ix, iy int) diff.Result {
  131. return diff.BoolResult(ssx[ix] == ssy[iy])
  132. })
  133. esBytes := diff.Difference(len(sx), len(sy), func(ix, iy int) diff.Result {
  134. return diff.BoolResult(sx[ix] == sy[iy])
  135. })
  136. efficiencyLines := float64(esLines.Dist()) / float64(len(esLines))
  137. efficiencyBytes := float64(esBytes.Dist()) / float64(len(esBytes))
  138. isPureLinedText = efficiencyLines < 4*efficiencyBytes
  139. }
  140. }
  141. // Format the string into printable records.
  142. var list textList
  143. var delim string
  144. switch {
  145. // If the text appears to be multi-lined text,
  146. // then perform differencing across individual lines.
  147. case isPureLinedText:
  148. list = opts.formatDiffSlice(
  149. reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line",
  150. func(v reflect.Value, d diffMode) textRecord {
  151. s := formatString(v.Index(0).String())
  152. return textRecord{Diff: d, Value: textLine(s)}
  153. },
  154. )
  155. delim = "\n"
  156. // If possible, use a custom triple-quote (""") syntax for printing
  157. // differences in a string literal. This format is more readable,
  158. // but has edge-cases where differences are visually indistinguishable.
  159. // This format is avoided under the following conditions:
  160. // • A line starts with `"""`
  161. // • A line starts with "..."
  162. // • A line contains non-printable characters
  163. // • Adjacent different lines differ only by whitespace
  164. //
  165. // For example:
  166. // """
  167. // ... // 3 identical lines
  168. // foo
  169. // bar
  170. // - baz
  171. // + BAZ
  172. // """
  173. isTripleQuoted := true
  174. prevRemoveLines := map[string]bool{}
  175. prevInsertLines := map[string]bool{}
  176. var list2 textList
  177. list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true})
  178. for _, r := range list {
  179. if !r.Value.Equal(textEllipsis) {
  180. line, _ := strconv.Unquote(string(r.Value.(textLine)))
  181. line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support
  182. normLine := strings.Map(func(r rune) rune {
  183. if unicode.IsSpace(r) {
  184. return -1 // drop whitespace to avoid visually indistinguishable output
  185. }
  186. return r
  187. }, line)
  188. isPrintable := func(r rune) bool {
  189. return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable
  190. }
  191. isTripleQuoted = !strings.HasPrefix(line, `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == ""
  192. switch r.Diff {
  193. case diffRemoved:
  194. isTripleQuoted = isTripleQuoted && !prevInsertLines[normLine]
  195. prevRemoveLines[normLine] = true
  196. case diffInserted:
  197. isTripleQuoted = isTripleQuoted && !prevRemoveLines[normLine]
  198. prevInsertLines[normLine] = true
  199. }
  200. if !isTripleQuoted {
  201. break
  202. }
  203. r.Value = textLine(line)
  204. r.ElideComma = true
  205. }
  206. if !(r.Diff == diffRemoved || r.Diff == diffInserted) { // start a new non-adjacent difference group
  207. prevRemoveLines = map[string]bool{}
  208. prevInsertLines = map[string]bool{}
  209. }
  210. list2 = append(list2, r)
  211. }
  212. if r := list2[len(list2)-1]; r.Diff == diffIdentical && len(r.Value.(textLine)) == 0 {
  213. list2 = list2[:len(list2)-1] // elide single empty line at the end
  214. }
  215. list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true})
  216. if isTripleQuoted {
  217. var out textNode = &textWrap{Prefix: "(", Value: list2, Suffix: ")"}
  218. switch t.Kind() {
  219. case reflect.String:
  220. if t != reflect.TypeOf(string("")) {
  221. out = opts.FormatType(t, out)
  222. }
  223. case reflect.Slice:
  224. // Always emit type for slices since the triple-quote syntax
  225. // looks like a string (not a slice).
  226. opts = opts.WithTypeMode(emitType)
  227. out = opts.FormatType(t, out)
  228. }
  229. return out
  230. }
  231. // If the text appears to be single-lined text,
  232. // then perform differencing in approximately fixed-sized chunks.
  233. // The output is printed as quoted strings.
  234. case isMostlyText:
  235. list = opts.formatDiffSlice(
  236. reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte",
  237. func(v reflect.Value, d diffMode) textRecord {
  238. s := formatString(v.String())
  239. return textRecord{Diff: d, Value: textLine(s)}
  240. },
  241. )
  242. // If the text appears to be binary data,
  243. // then perform differencing in approximately fixed-sized chunks.
  244. // The output is inspired by hexdump.
  245. case isBinary:
  246. list = opts.formatDiffSlice(
  247. reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte",
  248. func(v reflect.Value, d diffMode) textRecord {
  249. var ss []string
  250. for i := 0; i < v.Len(); i++ {
  251. ss = append(ss, formatHex(v.Index(i).Uint()))
  252. }
  253. s := strings.Join(ss, ", ")
  254. comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String())))
  255. return textRecord{Diff: d, Value: textLine(s), Comment: comment}
  256. },
  257. )
  258. // For all other slices of primitive types,
  259. // then perform differencing in approximately fixed-sized chunks.
  260. // The size of each chunk depends on the width of the element kind.
  261. default:
  262. var chunkSize int
  263. if t.Elem().Kind() == reflect.Bool {
  264. chunkSize = 16
  265. } else {
  266. switch t.Elem().Bits() {
  267. case 8:
  268. chunkSize = 16
  269. case 16:
  270. chunkSize = 12
  271. case 32:
  272. chunkSize = 8
  273. default:
  274. chunkSize = 8
  275. }
  276. }
  277. list = opts.formatDiffSlice(
  278. vx, vy, chunkSize, t.Elem().Kind().String(),
  279. func(v reflect.Value, d diffMode) textRecord {
  280. var ss []string
  281. for i := 0; i < v.Len(); i++ {
  282. switch t.Elem().Kind() {
  283. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  284. ss = append(ss, fmt.Sprint(v.Index(i).Int()))
  285. case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  286. ss = append(ss, fmt.Sprint(v.Index(i).Uint()))
  287. case reflect.Uint8, reflect.Uintptr:
  288. ss = append(ss, formatHex(v.Index(i).Uint()))
  289. case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
  290. ss = append(ss, fmt.Sprint(v.Index(i).Interface()))
  291. }
  292. }
  293. s := strings.Join(ss, ", ")
  294. return textRecord{Diff: d, Value: textLine(s)}
  295. },
  296. )
  297. }
  298. // Wrap the output with appropriate type information.
  299. var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"}
  300. if !isMostlyText {
  301. // The "{...}" byte-sequence literal is not valid Go syntax for strings.
  302. // Emit the type for extra clarity (e.g. "string{...}").
  303. if t.Kind() == reflect.String {
  304. opts = opts.WithTypeMode(emitType)
  305. }
  306. return opts.FormatType(t, out)
  307. }
  308. switch t.Kind() {
  309. case reflect.String:
  310. out = &textWrap{Prefix: "strings.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)}
  311. if t != reflect.TypeOf(string("")) {
  312. out = opts.FormatType(t, out)
  313. }
  314. case reflect.Slice:
  315. out = &textWrap{Prefix: "bytes.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)}
  316. if t != reflect.TypeOf([]byte(nil)) {
  317. out = opts.FormatType(t, out)
  318. }
  319. }
  320. return out
  321. }
  322. // formatASCII formats s as an ASCII string.
  323. // This is useful for printing binary strings in a semi-legible way.
  324. func formatASCII(s string) string {
  325. b := bytes.Repeat([]byte{'.'}, len(s))
  326. for i := 0; i < len(s); i++ {
  327. if ' ' <= s[i] && s[i] <= '~' {
  328. b[i] = s[i]
  329. }
  330. }
  331. return string(b)
  332. }
  333. func (opts formatOptions) formatDiffSlice(
  334. vx, vy reflect.Value, chunkSize int, name string,
  335. makeRec func(reflect.Value, diffMode) textRecord,
  336. ) (list textList) {
  337. eq := func(ix, iy int) bool {
  338. return vx.Index(ix).Interface() == vy.Index(iy).Interface()
  339. }
  340. es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result {
  341. return diff.BoolResult(eq(ix, iy))
  342. })
  343. appendChunks := func(v reflect.Value, d diffMode) int {
  344. n0 := v.Len()
  345. for v.Len() > 0 {
  346. n := chunkSize
  347. if n > v.Len() {
  348. n = v.Len()
  349. }
  350. list = append(list, makeRec(v.Slice(0, n), d))
  351. v = v.Slice(n, v.Len())
  352. }
  353. return n0 - v.Len()
  354. }
  355. var numDiffs int
  356. maxLen := -1
  357. if opts.LimitVerbosity {
  358. maxLen = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc...
  359. opts.VerbosityLevel--
  360. }
  361. groups := coalesceAdjacentEdits(name, es)
  362. groups = coalesceInterveningIdentical(groups, chunkSize/4)
  363. groups = cleanupSurroundingIdentical(groups, eq)
  364. maxGroup := diffStats{Name: name}
  365. for i, ds := range groups {
  366. if maxLen >= 0 && numDiffs >= maxLen {
  367. maxGroup = maxGroup.Append(ds)
  368. continue
  369. }
  370. // Print equal.
  371. if ds.NumDiff() == 0 {
  372. // Compute the number of leading and trailing equal bytes to print.
  373. var numLo, numHi int
  374. numEqual := ds.NumIgnored + ds.NumIdentical
  375. for numLo < chunkSize*numContextRecords && numLo+numHi < numEqual && i != 0 {
  376. numLo++
  377. }
  378. for numHi < chunkSize*numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 {
  379. numHi++
  380. }
  381. if numEqual-(numLo+numHi) <= chunkSize && ds.NumIgnored == 0 {
  382. numHi = numEqual - numLo // Avoid pointless coalescing of single equal row
  383. }
  384. // Print the equal bytes.
  385. appendChunks(vx.Slice(0, numLo), diffIdentical)
  386. if numEqual > numLo+numHi {
  387. ds.NumIdentical -= numLo + numHi
  388. list.AppendEllipsis(ds)
  389. }
  390. appendChunks(vx.Slice(numEqual-numHi, numEqual), diffIdentical)
  391. vx = vx.Slice(numEqual, vx.Len())
  392. vy = vy.Slice(numEqual, vy.Len())
  393. continue
  394. }
  395. // Print unequal.
  396. len0 := len(list)
  397. nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved)
  398. vx = vx.Slice(nx, vx.Len())
  399. ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted)
  400. vy = vy.Slice(ny, vy.Len())
  401. numDiffs += len(list) - len0
  402. }
  403. if maxGroup.IsZero() {
  404. assert(vx.Len() == 0 && vy.Len() == 0)
  405. } else {
  406. list.AppendEllipsis(maxGroup)
  407. }
  408. return list
  409. }
  410. // coalesceAdjacentEdits coalesces the list of edits into groups of adjacent
  411. // equal or unequal counts.
  412. //
  413. // Example:
  414. //
  415. // Input: "..XXY...Y"
  416. // Output: [
  417. // {NumIdentical: 2},
  418. // {NumRemoved: 2, NumInserted 1},
  419. // {NumIdentical: 3},
  420. // {NumInserted: 1},
  421. // ]
  422. //
  423. func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) {
  424. var prevMode byte
  425. lastStats := func(mode byte) *diffStats {
  426. if prevMode != mode {
  427. groups = append(groups, diffStats{Name: name})
  428. prevMode = mode
  429. }
  430. return &groups[len(groups)-1]
  431. }
  432. for _, e := range es {
  433. switch e {
  434. case diff.Identity:
  435. lastStats('=').NumIdentical++
  436. case diff.UniqueX:
  437. lastStats('!').NumRemoved++
  438. case diff.UniqueY:
  439. lastStats('!').NumInserted++
  440. case diff.Modified:
  441. lastStats('!').NumModified++
  442. }
  443. }
  444. return groups
  445. }
  446. // coalesceInterveningIdentical coalesces sufficiently short (<= windowSize)
  447. // equal groups into adjacent unequal groups that currently result in a
  448. // dual inserted/removed printout. This acts as a high-pass filter to smooth
  449. // out high-frequency changes within the windowSize.
  450. //
  451. // Example:
  452. //
  453. // WindowSize: 16,
  454. // Input: [
  455. // {NumIdentical: 61}, // group 0
  456. // {NumRemoved: 3, NumInserted: 1}, // group 1
  457. // {NumIdentical: 6}, // ├── coalesce
  458. // {NumInserted: 2}, // ├── coalesce
  459. // {NumIdentical: 1}, // ├── coalesce
  460. // {NumRemoved: 9}, // └── coalesce
  461. // {NumIdentical: 64}, // group 2
  462. // {NumRemoved: 3, NumInserted: 1}, // group 3
  463. // {NumIdentical: 6}, // ├── coalesce
  464. // {NumInserted: 2}, // ├── coalesce
  465. // {NumIdentical: 1}, // ├── coalesce
  466. // {NumRemoved: 7}, // ├── coalesce
  467. // {NumIdentical: 1}, // ├── coalesce
  468. // {NumRemoved: 2}, // └── coalesce
  469. // {NumIdentical: 63}, // group 4
  470. // ]
  471. // Output: [
  472. // {NumIdentical: 61},
  473. // {NumIdentical: 7, NumRemoved: 12, NumInserted: 3},
  474. // {NumIdentical: 64},
  475. // {NumIdentical: 8, NumRemoved: 12, NumInserted: 3},
  476. // {NumIdentical: 63},
  477. // ]
  478. //
  479. func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats {
  480. groups, groupsOrig := groups[:0], groups
  481. for i, ds := range groupsOrig {
  482. if len(groups) >= 2 && ds.NumDiff() > 0 {
  483. prev := &groups[len(groups)-2] // Unequal group
  484. curr := &groups[len(groups)-1] // Equal group
  485. next := &groupsOrig[i] // Unequal group
  486. hadX, hadY := prev.NumRemoved > 0, prev.NumInserted > 0
  487. hasX, hasY := next.NumRemoved > 0, next.NumInserted > 0
  488. if ((hadX || hasX) && (hadY || hasY)) && curr.NumIdentical <= windowSize {
  489. *prev = prev.Append(*curr).Append(*next)
  490. groups = groups[:len(groups)-1] // Truncate off equal group
  491. continue
  492. }
  493. }
  494. groups = append(groups, ds)
  495. }
  496. return groups
  497. }
  498. // cleanupSurroundingIdentical scans through all unequal groups, and
  499. // moves any leading sequence of equal elements to the preceding equal group and
  500. // moves and trailing sequence of equal elements to the succeeding equal group.
  501. //
  502. // This is necessary since coalesceInterveningIdentical may coalesce edit groups
  503. // together such that leading/trailing spans of equal elements becomes possible.
  504. // Note that this can occur even with an optimal diffing algorithm.
  505. //
  506. // Example:
  507. //
  508. // Input: [
  509. // {NumIdentical: 61},
  510. // {NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements
  511. // {NumIdentical: 67},
  512. // {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // assume 10 trailing identical elements
  513. // {NumIdentical: 54},
  514. // ]
  515. // Output: [
  516. // {NumIdentical: 64}, // incremented by 3
  517. // {NumRemoved: 9},
  518. // {NumIdentical: 67},
  519. // {NumRemoved: 9},
  520. // {NumIdentical: 64}, // incremented by 10
  521. // ]
  522. //
  523. func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats {
  524. var ix, iy int // indexes into sequence x and y
  525. for i, ds := range groups {
  526. // Handle equal group.
  527. if ds.NumDiff() == 0 {
  528. ix += ds.NumIdentical
  529. iy += ds.NumIdentical
  530. continue
  531. }
  532. // Handle unequal group.
  533. nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified
  534. ny := ds.NumIdentical + ds.NumInserted + ds.NumModified
  535. var numLeadingIdentical, numTrailingIdentical int
  536. for i := 0; i < nx && i < ny && eq(ix+i, iy+i); i++ {
  537. numLeadingIdentical++
  538. }
  539. for i := 0; i < nx && i < ny && eq(ix+nx-1-i, iy+ny-1-i); i++ {
  540. numTrailingIdentical++
  541. }
  542. if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 {
  543. if numLeadingIdentical > 0 {
  544. // Remove leading identical span from this group and
  545. // insert it into the preceding group.
  546. if i-1 >= 0 {
  547. groups[i-1].NumIdentical += numLeadingIdentical
  548. } else {
  549. // No preceding group exists, so prepend a new group,
  550. // but do so after we finish iterating over all groups.
  551. defer func() {
  552. groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...)
  553. }()
  554. }
  555. // Increment indexes since the preceding group would have handled this.
  556. ix += numLeadingIdentical
  557. iy += numLeadingIdentical
  558. }
  559. if numTrailingIdentical > 0 {
  560. // Remove trailing identical span from this group and
  561. // insert it into the succeeding group.
  562. if i+1 < len(groups) {
  563. groups[i+1].NumIdentical += numTrailingIdentical
  564. } else {
  565. // No succeeding group exists, so append a new group,
  566. // but do so after we finish iterating over all groups.
  567. defer func() {
  568. groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical})
  569. }()
  570. }
  571. // Do not increment indexes since the succeeding group will handle this.
  572. }
  573. // Update this group since some identical elements were removed.
  574. nx -= numIdentical
  575. ny -= numIdentical
  576. groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny}
  577. }
  578. ix += nx
  579. iy += ny
  580. }
  581. return groups
  582. }