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 // Same contents as MatchAlphabet, but an array is much faster to index than a map.
40 var s [256]int
41 for i := 0; i < len(pattern); i++ {
42 s[pattern[i]] |= int(uint(1) << uint(len(pattern)-i-1))
43 }
44
45 // Highest score beyond which we give up.
46 scoreThreshold := dmp.MatchThreshold
47 // Is there a nearby exact match? (speedup)
48 bestLoc := indexOf(text, pattern, loc)
49 if bestLoc != -1 {
50 scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
51 pattern), scoreThreshold)
52 // What about in the other direction? (speedup)
53 bestLoc = lastIndexOf(text, pattern, loc+len(pattern))
54 if bestLoc != -1 {
55 scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc,
56 pattern), scoreThreshold)
57 }
58 }
59
60 // Initialise the bit arrays.
61 matchmask := 1 << uint((len(pattern) - 1))
62 bestLoc = -1
63
64 var binMin, binMid int
65 binMax := len(pattern) + len(text)
66 lastRd := []int{}
67 for d := 0; d < len(pattern); d++ {
68 // 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.
69 binMin = 0
70 binMid = binMax
71 for binMin < binMid {
72 if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold {
73 binMin = binMid
74 } else {
75 binMax = binMid
76 }
77 binMid = (binMax-binMin)/2 + binMin
78 }
79 // Use the result from this iteration as the maximum for the next.
80 binMax = binMid
81 start := int(math.Max(1, float64(loc-binMid+1)))
82 finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern)))
83
84 rd := make([]int, finish+2)
85 rd[finish+1] = (1 << uint(d)) - 1
86
87 for j := finish; j >= start; j-- {
88 var charMatch int
89 if len(text) > j-1 {
90 // Characters not in the pattern map to 0.
91 charMatch = s[text[j-1]]
92 }
93
94 if d == 0 {

Callers 3

MatchMainMethod · 0.95
TestMatchBitapFunction · 0.80
BenchmarkMatchBitapFunction · 0.80

Calls 3

matchBitapScoreMethod · 0.95
indexOfFunction · 0.85
lastIndexOfFunction · 0.85

Tested by 2

TestMatchBitapFunction · 0.64
BenchmarkMatchBitapFunction · 0.64