Skip to content
Myr

Consolidate Result and rank structs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

By not storing item index twice, we can cut down the size of Result struct and now it makes more sense to store and pass Results by values. Benchmarks show no degradation of performance by additional pointer indirection for looking up index.

authored by Junegunn Choi · committed by Junegunn Choi · parent 5e72709 · Browse files · 9 files+65 added−68 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+65 added−68 removed

  • other:+65 added−68 removed

9 files+65 added−68 removed

modified:src/cache_test.go+2 added-2 removed
5 unmodified lines
6 cache := NewChunkCache()7 chunk2 := make(Chunk, chunkSize)8 chunk1p := &Chunk{}9 chunk2p := &chunk210 items1 := []*Result{&Result{}}11 items2 := []*Result{&Result{}, &Result{}}10 items1 := []Result{Result{}}11 items2 := []Result{Result{}, Result{}}12 cache.Add(chunk1p, "foo", items1)13 cache.Add(chunk2p, "foo", items1)14 cache.Add(chunk2p, "bar", items2)15
25 unmodified lines
modified:src/cache.go+4 added-4 removed
1 unmodified line
23import "sync"45// queryCache associates strings to lists of items6type queryCache map[string][]*Result6type queryCache map[string][]Result78// ChunkCache associates Chunk and query string to lists of items9type ChunkCache struct {10 mutex sync.Mutex
5 unmodified lines
16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17}1819// Add adds the list to the cache20func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {20func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {21 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {22 return23 }24
8 unmodified lines
33 (*qc)[key] = list34}3536// Lookup is called to lookup ChunkCache37func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []*Result {37func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {38 if len(key) == 0 || !chunk.IsFull() {39 return nil40 }41
9 unmodified lines
51 }52 return nil53}5455func (cc *ChunkCache) Search(chunk *Chunk, key string) []*Result {55func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {56 if len(key) == 0 || !chunk.IsFull() {57 return nil58 }59
22 unmodified lines
modified:src/matcher.go+4 added-4 removed
129 unmodified lines
130}131132type partialResult struct {133 index int134 matches []*Result134 matches []Result135}136137func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {138 startedAt := time.Now()
22 unmodified lines
161 }162 go func(idx int, slab *util.Slab, chunks []*Chunk) {163 defer func() { waitGroup.Done() }()164 count := 0165 allMatches := make([][]*Result, len(chunks))165 allMatches := make([][]Result, len(chunks))166 for idx, chunk := range chunks {167 matches := request.pattern.Match(chunk, slab)168 allMatches[idx] = matches169 count += len(matches)
1 unmodified line
171 return172 }173 countChan <- len(matches)174 }175 sliceMatches := make([]*Result, 0, count)175 sliceMatches := make([]Result, 0, count)176 for _, matches := range allMatches {177 sliceMatches = append(sliceMatches, matches...)178 }179 if m.sort {
31 unmodified lines
211 m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))212 }213 }214215 partialResults := make([][]*Result, numSlices)215 partialResults := make([][]Result, numSlices)216 for _ = range slices {217 partialResult := <-resultChan218 partialResults[partialResult.index] = partialResult.matches219 }
15 unmodified lines
modified:src/merger_test.go+8 added-8 removed
13 unmodified lines
14 t.Error(msg)15 }16}1718func randResult() *Result {18func randResult() Result {19 str := fmt.Sprintf("%d", rand.Uint32())20 return &Result{21 item: &Item{text: util.RunesToChars([]rune(str))},22 rank: rank{index: rand.Int31()}}20 chars := util.RunesToChars([]rune(str))21 chars.Index = rand.Int31()22 return Result{item: &Item{text: chars}}23}2425func TestEmptyMerger(t *testing.T) {26 assert(t, EmptyMerger.Length() == 0, "Not empty")
1 unmodified line
28 assert(t, len(EmptyMerger.lists) == 0, "Invalid lists")29 assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")30}3132func buildLists(partiallySorted bool) ([][]*Result, []*Result) {32func buildLists(partiallySorted bool) ([][]Result, []Result) {33 numLists := 434 lists := make([][]*Result, numLists)34 lists := make([][]Result, numLists)35 cnt := 036 for i := 0; i < numLists; i++ {37 numResults := rand.Int() % 2038 cnt += numResults39 lists[i] = make([]*Result, numResults)39 lists[i] = make([]Result, numResults)40 for j := 0; j < numResults; j++ {41 item := randResult()42 lists[i][j] = item43 }44 if partiallySorted {45 sort.Sort(ByRelevance(lists[i]))46 }47 }48 items := []*Result{}48 items := []Result{}49 for _, list := range lists {50 items = append(items, list...)51 }52 return lists, items
36 unmodified lines
modified:src/merger.go+9 added-9 removed
1 unmodified line
23import "fmt"45// EmptyMerger is a Merger with no data6var EmptyMerger = NewMerger(nil, [][]*Result{}, false, false)6var EmptyMerger = NewMerger(nil, [][]Result{}, false, false)78// Merger holds a set of locally sorted lists of items and provides the view of9// a single, globally-sorted list10type Merger struct {11 pattern *Pattern12 lists [][]*Result13 merged []*Result12 lists [][]Result13 merged []Result14 chunks *[]*Chunk15 cursors []int16 sorted bool17 tac bool
16 unmodified lines
34 return &mg35}3637// NewMerger returns a new Merger38func NewMerger(pattern *Pattern, lists [][]*Result, sorted bool, tac bool) *Merger {38func NewMerger(pattern *Pattern, lists [][]Result, sorted bool, tac bool) *Merger {39 mg := Merger{40 pattern: pattern,41 lists: lists,42 merged: []*Result{},42 merged: []Result{},43 chunks: nil,44 cursors: make([]int, len(lists)),45 sorted: sorted,46 tac: tac,
11 unmodified lines
58 return mg.count59}6061// Get returns the pointer to the Result object indexed by the given integer62func (mg *Merger) Get(idx int) *Result {62func (mg *Merger) Get(idx int) Result {63 if mg.chunks != nil {64 if mg.tac {65 idx = mg.count - idx - 166 }67 chunk := (*mg.chunks)[idx/chunkSize]68 return &Result{item: &(*chunk)[idx%chunkSize]}68 return Result{item: &(*chunk)[idx%chunkSize]}69 }7071 if mg.sorted {72 return mg.mergedGet(idx)
15 unmodified lines
88func (mg *Merger) cacheable() bool {89 return mg.count < mergerCacheMax90}9192func (mg *Merger) mergedGet(idx int) *Result {92func (mg *Merger) mergedGet(idx int) Result {93 for i := len(mg.merged); i <= idx; i++ {94 minRank := minRank()95 minIdx := -196 for listIdx, list := range mg.lists {
2 unmodified lines
99 mg.cursors[listIdx] = -1100 continue101 }102 if cursor >= 0 {103 rank := list[cursor].rank103 rank := list[cursor]104 if minIdx < 0 || compareRanks(rank, minRank, mg.tac) {105 minRank = rank106 minIdx = listIdx107 }
14 unmodified lines
modified:src/pattern.go+9 added-7 removed
241 unmodified lines
242 return strings.Join(cacheableTerms, " ")243}244245// Match returns the list of matches Items in the given Chunk246func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {246func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {247 // ChunkCache: Exact match248 cacheKey := p.CacheKey()249 if p.cacheable {250 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {
11 unmodified lines
262 }263 return matches264}265266func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {267 matches := []*Result{}266func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {267 matches := []Result{}268269 if space == nil {270 for idx := range *chunk {271 if match, _, _ := p.MatchItem(&(*chunk)[idx], false, slab); match != nil {272 matches = append(matches, match)272 matches = append(matches, *match)273 }274 }275 } else {276 for _, result := range space {277 if match, _, _ := p.MatchItem(result.item, false, slab); match != nil {278 matches = append(matches, match)278 matches = append(matches, *match)279 }280 }281 }282 return matches
2 unmodified lines
285// MatchItem returns true if the Item is a match286func (p *Pattern) MatchItem(item *Item, withPos bool, slab *util.Slab) (*Result, []Offset, *[]int) {287 if p.extended {288 if offsets, bonus, pos := p.extendedMatch(item, withPos, slab); len(offsets) == len(p.termSets) {289 return buildResult(item, offsets, bonus), offsets, pos289 result := buildResult(item, offsets, bonus)290 return &result, offsets, pos291 }292 return nil, nil, nil293 }294 offset, bonus, pos := p.basicMatch(item, withPos, slab)295 if sidx := offset[0]; sidx >= 0 {296 offsets := []Offset{offset}296 return buildResult(item, offsets, bonus), offsets, pos297 result := buildResult(item, offsets, bonus)298 return &result, offsets, pos299 }300 return nil, nil, nil301}302
83 unmodified lines
modified:src/result_test.go+11 added-11 removed
29 unmodified lines
30 }31}3233func TestRankComparison(t *testing.T) {34 rank := func(vals ...uint16) rank {35 return rank{34 rank := func(vals ...uint16) Result {35 return Result{36 points: [4]uint16{vals[0], vals[1], vals[2], vals[3]},37 index: int32(vals[4])}37 item: &Item{text: util.Chars{Index: int32(vals[4])}}}38 }39 if compareRanks(rank(3, 0, 0, 0, 5), rank(2, 0, 0, 0, 7), false) ||40 !compareRanks(rank(3, 0, 0, 0, 5), rank(3, 0, 0, 0, 6), false) ||41 !compareRanks(rank(1, 2, 0, 0, 3), rank(1, 3, 0, 0, 2), false) ||
16 unmodified lines
5859 strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}60 item1 := buildResult(61 withIndex(&Item{text: util.RunesToChars(strs[0])}, 1), []Offset{}, 2)62 if item1.rank.points[0] != math.MaxUint16-2 || // Bonus63 item1.rank.points[1] != 3 || // Length64 item1.rank.points[2] != 0 || // Unused65 item1.rank.points[3] != 0 || // Unused62 if item1.points[0] != math.MaxUint16-2 || // Bonus63 item1.points[1] != 3 || // Length64 item1.points[2] != 0 || // Unused65 item1.points[3] != 0 || // Unused66 item1.item.Index() != 1 {67 t.Error(item1.rank)67 t.Error(item1)68 }69 // Only differ in index70 item2 := buildResult(&Item{text: util.RunesToChars(strs[0])}, []Offset{}, 2)7172 items := []*Result{item1, item2}72 items := []Result{item1, item2}73 sort.Sort(ByRelevance(items))74 if items[0] != item2 || items[1] != item1 {75 t.Error(items)76 }7778 items = []*Result{item2, item1, item1, item2}78 items = []Result{item2, item1, item1, item2}79 sort.Sort(ByRelevance(items))80 if items[0] != item2 || items[1] != item2 ||81 items[2] != item1 || items[3] != item1 {82 t.Error(items, item1, item1.item.Index(), item2, item2.item.Index())
7 unmodified lines
90 item5 := buildResult(91 withIndex(&Item{}, 2), []Offset{Offset{1, 3}, Offset{5, 7}}, 5)92 item6 := buildResult(93 withIndex(&Item{}, 2), []Offset{Offset{1, 2}, Offset{6, 7}}, 6)94 items = []*Result{item1, item2, item3, item4, item5, item6}94 items = []Result{item1, item2, item3, item4, item5, item6}95 sort.Sort(ByRelevance(items))96 if !(items[0] == item6 && items[1] == item5 &&97 items[2] == item4 && items[3] == item3 &&98 items[4] == item2 && items[5] == item1) {
38 unmodified lines
modified:src/result.go+14 added-19 removed
17 unmodified lines
18 attr tui.Attr19 index int3220}2122type rank struct {22type Result struct {23 item *Item24 points [4]uint1624 index int3225}2627type Result struct {28 item *Item29 rank rank30}3132func buildResult(item *Item, offsets []Offset, score int) *Result {27func buildResult(item *Item, offsets []Offset, score int) Result {28 if len(offsets) > 1 {29 sort.Sort(ByOrder(offsets))30 }3137 result := Result{item: item, rank: rank{index: item.Index()}}32 result := Result{item: item}33 numChars := item.text.Length()34 minBegin := math.MaxUint1635 minEnd := math.MaxUint1636 maxEnd := 0
32 unmodified lines
69 val = util.AsUint16(math.MaxUint16 - math.MaxUint16*(maxEnd-whitePrefixLen)/int(item.TrimLength()))70 }71 }72 }78 result.rank.points[idx] = val73 result.points[idx] = val74 }7581 return &result76 return result77}7879// Sort criteria to use. Never changes once fzf is started.80var sortCriteria []criterion
2 unmodified lines
83func (result *Result) Index() int32 {84 return result.item.Index()85}8692func minRank() rank {93 return rank{index: 0, points: [4]uint16{math.MaxUint16, 0, 0, 0}}87func minRank() Result {88 return Result{item: &nilItem, points: [4]uint16{math.MaxUint16, 0, 0, 0}}89}9091func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme, color tui.ColorPair, attr tui.Attr, current bool) []colorOffset {92 itemColors := result.item.Colors()
102 unmodified lines
195 return (ioff[0] < joff[0]) || (ioff[0] == joff[0]) && (ioff[1] <= joff[1])196}197198// ByRelevance is for sorting Items204type ByRelevance []*Result199type ByRelevance []Result200201func (a ByRelevance) Len() int {202 return len(a)203}
2 unmodified lines
206 a[i], a[j] = a[j], a[i]207}208209func (a ByRelevance) Less(i, j int) bool {215 return compareRanks((*a[i]).rank, (*a[j]).rank, false)210 return compareRanks(a[i], a[j], false)211}212213// ByRelevanceTac is for sorting Items219type ByRelevanceTac []*Result214type ByRelevanceTac []Result215216func (a ByRelevanceTac) Len() int {217 return len(a)218}
2 unmodified lines
221 a[i], a[j] = a[j], a[i]222}223224func (a ByRelevanceTac) Less(i, j int) bool {230 return compareRanks((*a[i]).rank, (*a[j]).rank, true)225 return compareRanks(a[i], a[j], true)226}227233func compareRanks(irank rank, jrank rank, tac bool) bool {228func compareRanks(irank Result, jrank Result, tac bool) bool {229 for idx := 0; idx < 4; idx++ {230 left := irank.points[idx]231 right := jrank.points[idx]232 if left < right {
1 unmodified line
234 } else if left > right {235 return false236 }237 }243 return (irank.index <= jrank.index) != tac238 return (irank.item.Index() <= jrank.item.Index()) != tac239}
modified:src/terminal.go+4 added-4 removed
712 unmodified lines
713 text: util.RunesToChars([]rune(trimmed)),714 colors: colors}715716 t.move(line, 2, true)717 t.printHighlighted(&Result{item: item},717 t.printHighlighted(Result{item: item},718 tui.AttrRegular, tui.ColHeader, tui.ColDefault, false, false)719 }720}721
19 unmodified lines
741 }742 }743}744745func (t *Terminal) printItem(result *Result, line int, i int, current bool) {745func (t *Terminal) printItem(result Result, line int, i int, current bool) {746 item := result.item747 _, selected := t.selected[item.Index()]748 label := " "749 if t.jumping != jumpDisabled {
7 unmodified lines
757 }758759 // Avoid unnecessary redraw760 newLine := itemLine{current: current, selected: selected, label: label,761 result: *result, queryLen: len(t.input), width: 0}761 result: result, queryLen: len(t.input), width: 0}762 prevLine := t.prevLines[i]763 if prevLine.current == newLine.current &&764 prevLine.selected == newLine.selected &&765 prevLine.label == newLine.label &&
73 unmodified lines
839func (t *Terminal) overflow(runes []rune, max int) bool {840 return t.displayWidthWithLimit(runes, 0, max) > max841}842843func (t *Terminal) printHighlighted(result *Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {843func (t *Terminal) printHighlighted(result Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {844 item := result.item845846 // Overflow847 text := make([]rune, item.text.Length())
991 unmodified lines