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
Provenance
- Commit
bbe10f4- Tree
f166d6e- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
5e72709
9 files changed+65 added−68 removed
modified:src/cache_test.go+2 added-2 removed
5 unmodified lines6 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 linesmodified:src/cache.go+4 added-4 removed
1 unmodified line2 3 import "sync"4 5 // queryCache associates strings to lists of items6-type queryCache map[string][]*Result6+type queryCache map[string][]Result7 8 // ChunkCache associates Chunk and query string to lists of items9 type ChunkCache struct {10 mutex sync.Mutex5 unmodified lines16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17 }18 19 // Add adds the list to the cache20-func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Result) {20+func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {21 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {22 return23 }24 8 unmodified lines33 (*qc)[key] = list34 }35 36 // Lookup is called to lookup ChunkCache37-func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []*Result {37+func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {38 if len(key) == 0 || !chunk.IsFull() {39 return nil40 }41 9 unmodified lines51 }52 return nil53 }54 55-func (cc *ChunkCache) Search(chunk *Chunk, key string) []*Result {55+func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {56 if len(key) == 0 || !chunk.IsFull() {57 return nil58 }59 22 unmodified linesmodified:src/matcher.go+4 added-4 removed
129 unmodified lines130 }131 132 type partialResult struct {133 index int134- matches []*Result134+ matches []Result135 }136 137 func (m *Matcher) scan(request MatchRequest) (*Merger, bool) {138 startedAt := time.Now()22 unmodified lines161 }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 line171 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 lines211 m.eventBox.Set(EvtSearchProgress, float32(count)/float32(numChunks))212 }213 }214 215- partialResults := make([][]*Result, numSlices)215+ partialResults := make([][]Result, numSlices)216 for _ = range slices {217 partialResult := <-resultChan218 partialResults[partialResult.index] = partialResult.matches219 }15 unmodified linesmodified:src/merger_test.go+8 added-8 removed
13 unmodified lines14 t.Error(msg)15 }16 }17 18-func randResult() *Result {18+func 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 }24 25 func TestEmptyMerger(t *testing.T) {26 assert(t, EmptyMerger.Length() == 0, "Not empty")1 unmodified line28 assert(t, len(EmptyMerger.lists) == 0, "Invalid lists")29 assert(t, len(EmptyMerger.merged) == 0, "Invalid merged list")30 }31 32-func buildLists(partiallySorted bool) ([][]*Result, []*Result) {32+func 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, items36 unmodified linesmodified:src/merger.go+9 added-9 removed
1 unmodified line2 3 import "fmt"4 5 // EmptyMerger is a Merger with no data6-var EmptyMerger = NewMerger(nil, [][]*Result{}, false, false)6+var EmptyMerger = NewMerger(nil, [][]Result{}, false, false)7 8 // Merger holds a set of locally sorted lists of items and provides the view of9 // a single, globally-sorted list10 type Merger struct {11 pattern *Pattern12- lists [][]*Result13- merged []*Result12+ lists [][]Result13+ merged []Result14 chunks *[]*Chunk15 cursors []int16 sorted bool17 tac bool16 unmodified lines34 return &mg35 }36 37 // NewMerger returns a new Merger38-func NewMerger(pattern *Pattern, lists [][]*Result, sorted bool, tac bool) *Merger {38+func 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 lines58 return mg.count59 }60 61 // Get returns the pointer to the Result object indexed by the given integer62-func (mg *Merger) Get(idx int) *Result {62+func (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 }70 71 if mg.sorted {72 return mg.mergedGet(idx)15 unmodified lines88 func (mg *Merger) cacheable() bool {89 return mg.count < mergerCacheMax90 }91 92-func (mg *Merger) mergedGet(idx int) *Result {92+func (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 lines99 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 linesmodified:src/pattern.go+9 added-7 removed
241 unmodified lines242 return strings.Join(cacheableTerms, " ")243 }244 245 // Match returns the list of matches Items in the given Chunk246-func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []*Result {246+func (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 lines262 }263 return matches264 }265 266-func (p *Pattern) matchChunk(chunk *Chunk, space []*Result, slab *util.Slab) []*Result {267- matches := []*Result{}266+func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {267+ matches := []Result{}268 269 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 matches2 unmodified lines285 // MatchItem returns true if the Item is a match286 func (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 linesmodified:src/result_test.go+11 added-11 removed
29 unmodified lines30 }31 }32 33 func 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 lines58 59 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)71 72- 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 }77 78- 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 lines90 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 linesmodified:src/result.go+14 added-19 removed
17 unmodified lines18 attr tui.Attr19 index int3220 }21 22-type rank struct {22+type Result struct {23+ item *Item24 points [4]uint1624- index int3225 }26 27-type Result struct {28- item *Item29- rank rank30-}31-32-func buildResult(item *Item, offsets []Offset, score int) *Result {27+func buildResult(item *Item, offsets []Offset, score int) Result {28 if len(offsets) > 1 {29 sort.Sort(ByOrder(offsets))30 }31 37- 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 := 032 unmodified lines69 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 }75 81- return &result76+ return result77 }78 79 // Sort criteria to use. Never changes once fzf is started.80 var sortCriteria []criterion2 unmodified lines83 func (result *Result) Index() int32 {84 return result.item.Index()85 }86 92-func minRank() rank {93- return rank{index: 0, points: [4]uint16{math.MaxUint16, 0, 0, 0}}87+func minRank() Result {88+ return Result{item: &nilItem, points: [4]uint16{math.MaxUint16, 0, 0, 0}}89 }90 91 func (result *Result) colorOffsets(matchOffsets []Offset, theme *tui.ColorTheme, color tui.ColorPair, attr tui.Attr, current bool) []colorOffset {92 itemColors := result.item.Colors()102 unmodified lines195 return (ioff[0] < joff[0]) || (ioff[0] == joff[0]) && (ioff[1] <= joff[1])196 }197 198 // ByRelevance is for sorting Items204-type ByRelevance []*Result199+type ByRelevance []Result200 201 func (a ByRelevance) Len() int {202 return len(a)203 }2 unmodified lines206 a[i], a[j] = a[j], a[i]207 }208 209 func (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 }212 213 // ByRelevanceTac is for sorting Items219-type ByRelevanceTac []*Result214+type ByRelevanceTac []Result215 216 func (a ByRelevanceTac) Len() int {217 return len(a)218 }2 unmodified lines221 a[i], a[j] = a[j], a[i]222 }223 224 func (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 }227 233-func compareRanks(irank rank, jrank rank, tac bool) bool {228+func 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 line234 } 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 lines713 text: util.RunesToChars([]rune(trimmed)),714 colors: colors}715 716 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 lines741 }742 }743 }744 745-func (t *Terminal) printItem(result *Result, line int, i int, current bool) {745+func (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 lines757 }758 759 // 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 lines839 func (t *Terminal) overflow(runes []rune, max int) bool {840 return t.displayWidthWithLimit(runes, 0, max) > max841 }842 843-func (t *Terminal) printHighlighted(result *Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {843+func (t *Terminal) printHighlighted(result Result, attr tui.Attr, col1 tui.ColorPair, col2 tui.ColorPair, current bool, match bool) int {844 item := result.item845 846 // Overflow847 text := make([]rune, item.text.Length())991 unmodified lines