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.
(runes1, runes2 []rune, deadline time.Time)
| 261 | // diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff. |
| 262 | // See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations. |
| 263 | func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff { |
| 264 | // Cache the text lengths to prevent multiple calls. |
| 265 | runes1Len, runes2Len := len(runes1), len(runes2) |
| 266 | |
| 267 | maxD := (runes1Len + runes2Len + 1) / 2 |
| 268 | vOffset := maxD |
| 269 | vLength := 2 * maxD |
| 270 | |
| 271 | v1 := make([]int, vLength) |
| 272 | v2 := make([]int, vLength) |
| 273 | for i := range v1 { |
| 274 | v1[i] = -1 |
| 275 | v2[i] = -1 |
| 276 | } |
| 277 | v1[vOffset+1] = 0 |
| 278 | v2[vOffset+1] = 0 |
| 279 | |
| 280 | delta := runes1Len - runes2Len |
| 281 | // If the total number of characters is odd, then the front path will collide with the reverse path. |
| 282 | front := (delta%2 != 0) |
| 283 | // Offsets for start and end of k loop. Prevents mapping of space beyond the grid. |
| 284 | k1start := 0 |
| 285 | k1end := 0 |
| 286 | k2start := 0 |
| 287 | k2end := 0 |
| 288 | for d := 0; d < maxD; d++ { |
| 289 | // Bail out if deadline is reached. |
| 290 | if !deadline.IsZero() && d%16 == 0 && time.Now().After(deadline) { |
| 291 | break |
| 292 | } |
| 293 | |
| 294 | // Walk the front path one step. |
| 295 | for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 { |
| 296 | k1Offset := vOffset + k1 |
| 297 | var x1 int |
| 298 | |
| 299 | if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) { |
| 300 | x1 = v1[k1Offset+1] |
| 301 | } else { |
| 302 | x1 = v1[k1Offset-1] + 1 |
| 303 | } |
| 304 | |
| 305 | y1 := x1 - k1 |
| 306 | for x1 < runes1Len && y1 < runes2Len { |
| 307 | if runes1[x1] != runes2[y1] { |
| 308 | break |
| 309 | } |
| 310 | x1++ |
| 311 | y1++ |
| 312 | } |
| 313 | v1[k1Offset] = x1 |
| 314 | if x1 > runes1Len { |
| 315 | // Ran off the right of the graph. |
| 316 | k1end += 2 |
| 317 | } else if y1 > runes2Len { |
| 318 | // Ran off the bottom of the graph. |
| 319 | k1start += 2 |
| 320 | } else if front { |
no test coverage detected