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

Method MatchBitap

diffmatchpatch/match.go:37–125  ·  view source on GitHub ↗

MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. Returns -1 if no match was found.

(text, pattern string, loc int)

Source from the content-addressed store, hash-verified

35// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm.
36// Returns -1 if no match was found.
37func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int {
38 // Initialise the alphabet.
39 s := dmp.MatchAlphabet(pattern)
40
41 // Highest score beyond which we give up.
42 scoreThreshold := dmp.MatchThreshold
43 // Is there a nearby exact match? (speedup)
44 bestLoc := indexOf(text, pattern, loc)
45 if bestLoc != -1 {
46 scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
47 pattern), scoreThreshold)
48 // What about in the other direction? (speedup)
49 bestLoc = lastIndexOf(text, pattern, loc+len(pattern))
50 if bestLoc != -1 {
51 scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
52 pattern), scoreThreshold)
53 }
54 }
55
56 // Initialise the bit arrays.
57 matchmask := 1 << uint((len(pattern) - 1))
58 bestLoc = -1
59
60 var binMin, binMid int
61 binMax := len(pattern) + len(text)
62 lastRd := []int{}
63 for d := 0; d < len(pattern); d++ {
64 // Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level.
65 binMin = 0
66 binMid = binMax
67 for binMin < binMid {
68 if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold {
69 binMin = binMid
70 } else {
71 binMax = binMid
72 }
73 binMid = (binMax-binMin)/2 + binMin
74 }
75 // Use the result from this iteration as the maximum for the next.
76 binMax = binMid
77 start := int(math.Max(1, float64(loc-binMid+1)))
78 finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern)))
79
80 rd := make([]int, finish+2)
81 rd[finish+1] = (1 << uint(d)) - 1
82
83 for j := finish; j >= start; j-- {
84 var charMatch int
85 if len(text) <= j-1 {
86 // Out of range.
87 charMatch = 0
88 } else if _, ok := s[text[j-1]]; !ok {
89 charMatch = 0
90 } else {
91 charMatch = s[text[j-1]]
92 }
93
94 if d == 0 {

Callers 2

MatchMainMethod · 0.95
TestMatchBitapFunction · 0.80

Calls 4

MatchAlphabetMethod · 0.95
matchBitapScoreMethod · 0.95
indexOfFunction · 0.85
lastIndexOfFunction · 0.85

Tested by 1

TestMatchBitapFunction · 0.64