You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fzf/src/matcher.go

253 lines
5.5 KiB
Go

10 years ago
package fzf
import (
"fmt"
"runtime"
"sort"
"sync"
10 years ago
"time"
"github.com/junegunn/fzf/src/util"
10 years ago
)
9 years ago
// MatchRequest represents a search request
10 years ago
type MatchRequest struct {
chunks []*Chunk
pattern *Pattern
final bool
sort bool
revision int
10 years ago
}
9 years ago
// Matcher is responsible for performing search
10 years ago
type Matcher struct {
cache *ChunkCache
10 years ago
patternBuilder func([]rune) *Pattern
sort bool
tac bool
eventBox *util.EventBox
reqBox *util.EventBox
10 years ago
partitions int
slab []*util.Slab
mergerCache map[string]*Merger
revision int
10 years ago
}
const (
reqRetry util.EventType = iota
9 years ago
reqReset
10 years ago
)
9 years ago
// NewMatcher returns a new Matcher
func NewMatcher(cache *ChunkCache, patternBuilder func([]rune) *Pattern,
sort bool, tac bool, eventBox *util.EventBox, revision int) *Matcher {
partitions := util.Min(numPartitionsMultiplier*runtime.NumCPU(), maxPartitions)
10 years ago
return &Matcher{
cache: cache,
10 years ago
patternBuilder: patternBuilder,
sort: sort,
tac: tac,
10 years ago
eventBox: eventBox,
reqBox: util.NewEventBox(),
partitions: partitions,
slab: make([]*util.Slab, partitions),
mergerCache: make(map[string]*Merger),
revision: revision}
10 years ago
}
9 years ago
// Loop puts Matcher in action
10 years ago
func (m *Matcher) Loop() {
prevCount := 0
for {
var request MatchRequest
stop := false
m.reqBox.Wait(func(events *util.Events) {
for t, val := range *events {
if t == reqQuit {
stop = true
return
}
10 years ago
switch val := val.(type) {
case MatchRequest:
request = val
default:
panic(fmt.Sprintf("Unexpected type: %T", val))
}
}
events.Clear()
})
if stop {
break
}
10 years ago
if request.sort != m.sort || request.revision != m.revision {
m.sort = request.sort
m.revision = request.revision
m.mergerCache = make(map[string]*Merger)
m.cache.Clear()
}
10 years ago
// Restart search
patternString := request.pattern.AsString()
var merger *Merger
10 years ago
cancelled := false
count := CountItems(request.chunks)
foundCache := false
if count == prevCount {
// Look up mergerCache
if cached, found := m.mergerCache[patternString]; found {
10 years ago
foundCache = true
merger = cached
10 years ago
}
} else {
// Invalidate mergerCache
10 years ago
prevCount = count
m.mergerCache = make(map[string]*Merger)
10 years ago
}
if !foundCache {
merger, cancelled = m.scan(request)
10 years ago
}
if !cancelled {
9 years ago
if merger.cacheable() {
m.mergerCache[patternString] = merger
}
merger.final = request.final
9 years ago
m.eventBox.Set(EvtSearchFin, merger)
10 years ago
}
}
}
func (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {
partitions := m.partitions
perSlice := len(chunks) / partitions
10 years ago
if perSlice == 0 {
partitions = len(chunks)
perSlice = 1
10 years ago
}
slices := make([][]*Chunk, partitions)
for i := 0; i < partitions; i++ {
10 years ago
start := i * perSlice
end := start + perSlice
if i == partitions-1 {
10 years ago
end = len(chunks)
}
slices[i] = chunks[start:end]
}
return slices
}
type partialResult struct {
index int
matches []Result
10 years ago
}
func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {
10 years ago
startedAt := time.Now()
numChunks := len(request.chunks)
if numChunks == 0 {
return EmptyMerger(request.revision), false
10 years ago
}
pattern := request.pattern
9 years ago
if pattern.IsEmpty() {
return PassMerger(&request.chunks, m.tac, request.revision), false
}
cancelled := util.NewAtomicBool(false)
10 years ago
slices := m.sliceChunks(request.chunks)
numSlices := len(slices)
resultChan := make(chan partialResult, numSlices)
countChan := make(chan int, numChunks)
waitGroup := sync.WaitGroup{}
10 years ago
for idx, chunks := range slices {
waitGroup.Add(1)
if m.slab[idx] == nil {
m.slab[idx] = util.MakeSlab(slab16Size, slab32Size)
}
go func(idx int, slab *util.Slab, chunks []*Chunk) {
defer func() { waitGroup.Done() }()
count := 0
allMatches := make([][]Result, len(chunks))
for idx, chunk := range chunks {
matches := request.pattern.Match(chunk, slab)
allMatches[idx] = matches
count += len(matches)
10 years ago
if cancelled.Get() {
return
}
countChan <- len(matches)
10 years ago
}
sliceMatches := make([]Result, 0, count)
for _, matches := range allMatches {
sliceMatches = append(sliceMatches, matches...)
}
9 years ago
if m.sort {
if m.tac {
sort.Sort(ByRelevanceTac(sliceMatches))
} else {
sort.Sort(ByRelevance(sliceMatches))
}
10 years ago
}
resultChan <- partialResult{idx, sliceMatches}
}(idx, m.slab[idx], chunks)
10 years ago
}
wait := func() bool {
cancelled.Set(true)
waitGroup.Wait()
return true
}
10 years ago
count := 0
matchCount := 0
for matchesInChunk := range countChan {
9 years ago
count++
10 years ago
matchCount += matchesInChunk
if count == numChunks {
break
}
9 years ago
if m.reqBox.Peek(reqReset) {
return nil, wait()
10 years ago
}
if time.Since(startedAt) > progressMinDuration {
9 years ago
m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))
10 years ago
}
}
partialResults := make([][]Result, numSlices)
for range slices {
10 years ago
partialResult := <-resultChan
partialResults[partialResult.index] = partialResult.matches
}
return NewMerger(pattern, partialResults, m.sort, m.tac, request.revision), false
10 years ago
}
9 years ago
// Reset is called to interrupt/signal the ongoing search
func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool, sort bool, revision int) {
10 years ago
pattern := m.patternBuilder(patternRunes)
var event util.EventType
10 years ago
if cancel {
9 years ago
event = reqReset
10 years ago
} else {
9 years ago
event = reqRetry
10 years ago
}
m.reqBox.Set(event, MatchRequest{chunks, pattern, final, sort && pattern.sortable, revision})
10 years ago
}
func (m *Matcher) Stop() {
m.reqBox.Set(reqQuit, nil)
}