MCPcopy Create free account
hub / github.com/pmezard/go-difflib / GetMatchingBlocks

Method GetMatchingBlocks

difflib/difflib.go:305–356  ·  view source on GitHub ↗

Return list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are adjacent triples in the list, and the second is no

()

Source from the content-addressed store, hash-verified

303// The last triple is a dummy, (len(a), len(b), 0), and is the only
304// triple with n==0.
305func (m *SequenceMatcher) GetMatchingBlocks() []Match {
306 if m.matchingBlocks != nil {
307 return m.matchingBlocks
308 }
309
310 var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
311 matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
312 match := m.findLongestMatch(alo, ahi, blo, bhi)
313 i, j, k := match.A, match.B, match.Size
314 if match.Size > 0 {
315 if alo < i && blo < j {
316 matched = matchBlocks(alo, i, blo, j, matched)
317 }
318 matched = append(matched, match)
319 if i+k < ahi && j+k < bhi {
320 matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
321 }
322 }
323 return matched
324 }
325 matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
326
327 // It's possible that we have adjacent equal blocks in the
328 // matching_blocks list now.
329 nonAdjacent := []Match{}
330 i1, j1, k1 := 0, 0, 0
331 for _, b := range matched {
332 // Is this block adjacent to i1, j1, k1?
333 i2, j2, k2 := b.A, b.B, b.Size
334 if i1+k1 == i2 && j1+k1 == j2 {
335 // Yes, so collapse them -- this just increases the length of
336 // the first block by the length of the second, and the first
337 // block so lengthened remains the block to compare against.
338 k1 += k2
339 } else {
340 // Not adjacent. Remember the first block (k1==0 means it's
341 // the dummy we started with), and make the second block the
342 // new block to compare against.
343 if k1 > 0 {
344 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
345 }
346 i1, j1, k1 = i2, j2, k2
347 }
348 }
349 if k1 > 0 {
350 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
351 }
352
353 nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
354 m.matchingBlocks = nonAdjacent
355 return m.matchingBlocks
356}
357
358// Return list of 5-tuples describing how to turn a into b.
359//

Callers 2

GetOpCodesMethod · 0.95
RatioMethod · 0.95

Calls 1

findLongestMatchMethod · 0.95

Tested by

no test coverage detected