MCPcopy Create free account
hub / github.com/sergi/go-diff / diffHalfMatch

Method diffHalfMatch

diffmatchpatch/diff.go:514–561  ·  view source on GitHub ↗
(text1, text2 []rune)

Source from the content-addressed store, hash-verified

512}
513
514func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune {
515 if dmp.DiffTimeout <= 0 {
516 // Don't risk returning a non-optimal diff if we have unlimited time.
517 return nil
518 }
519
520 var longtext, shorttext []rune
521 if len(text1) > len(text2) {
522 longtext = text1
523 shorttext = text2
524 } else {
525 longtext = text2
526 shorttext = text1
527 }
528
529 if len(longtext) < 4 || len(shorttext)*2 < len(longtext) {
530 return nil // Pointless.
531 }
532
533 // First check if the second quarter is the seed for a half-match.
534 hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4))
535
536 // Check again based on the third quarter.
537 hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2))
538
539 hm := [][]rune{}
540 if hm1 == nil && hm2 == nil {
541 return nil
542 } else if hm2 == nil {
543 hm = hm1
544 } else if hm1 == nil {
545 hm = hm2
546 } else {
547 // Both matched. Select the longest.
548 if len(hm1[4]) > len(hm2[4]) {
549 hm = hm1
550 } else {
551 hm = hm2
552 }
553 }
554
555 // A half-match was found, sort out the return data.
556 if len(text1) > len(text2) {
557 return hm
558 }
559
560 return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]}
561}
562
563// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext?
564// 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.

Callers 2

diffComputeMethod · 0.95
DiffHalfMatchMethod · 0.95

Calls 1

diffHalfMatchIMethod · 0.95

Tested by

no test coverage detected