Skip to content
Myr

Performance tuning - eager rune array conversion

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

> wc -l /tmp/list2 2594098 /tmp/list2 > time cat /tmp/list2 | fzf-0.10.1-darwin_amd64 -fqwerty > /dev/null real 0m5.418s user 0m10.990s sys 0m1.302s > time cat /tmp/list2 | fzf-head -fqwerty > /dev/null real 0m4.862s user 0m6.619s sys 0m0.982s

authored by Junegunn Choi · committed by Junegunn Choi · parent 634670e · Browse files · 18 files+162 added−153 removed
This commit

State

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

Diff stats

18 files+162 added−153 removed

  • other:+162 added−153 removed

18 files+162 added−153 removed

modified:src/algo/algo_test.go+2 added-3 removed
3 unmodified lines
4 "strings"5 "testing"6)78func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {8func assertMatch(t *testing.T, fun func(bool, []rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {9 if !caseSensitive {10 pattern = strings.ToLower(pattern)11 }12 runes := []rune(input)13 s, e := fun(caseSensitive, &runes, []rune(pattern))12 s, e := fun(caseSensitive, []rune(input), []rune(pattern))13 if s != sidx {14 t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)15 }16 if e != eidx {
35 unmodified lines
modified:src/algo/algo.go+13 added-13 removed
14 unmodified lines
15 * In short: They try to do as little work as possible.16 */1718// FuzzyMatch performs fuzzy-match19func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {19func FuzzyMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {20 if len(pattern) == 0 {21 return 0, 022 }23
9 unmodified lines
33 pidx := 034 sidx := -135 eidx := -13637 for index, char := range *runes {37 for index, char := range runes {38 // This is considerably faster than blindly applying strings.ToLower to the39 // whole string40 if !caseSensitive {41 // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable
18 unmodified lines
6061 if sidx >= 0 && eidx >= 0 {62 pidx--63 for index := eidx - 1; index >= sidx; index-- {64 char := (*runes)[index]64 char := runes[index]65 if !caseSensitive {66 if char >= 'A' && char <= 'Z' {67 char += 3268 } else if char > unicode.MaxASCII {
18 unmodified lines
87// strings and patterns are not very long.88//89// We might try to implement better algorithms in the future:90// http://en.wikipedia.org/wiki/String_searching_algorithm91func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {91func ExactMatchNaive(caseSensitive bool, runes []rune, pattern []rune) (int, int) {92 if len(pattern) == 0 {93 return 0, 094 }9596 numRunes := len(*runes)96 numRunes := len(runes)97 plen := len(pattern)98 if numRunes < plen {99 return -1, -1100 }101102 pidx := 0103 for index := 0; index < numRunes; index++ {104 char := (*runes)[index]104 char := runes[index]105 if !caseSensitive {106 if char >= 'A' && char <= 'Z' {107 char += 32108 } else if char > unicode.MaxASCII {
13 unmodified lines
122 return -1, -1123}124125// PrefixMatch performs prefix-match126func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {127 if len(*runes) < len(pattern) {126func PrefixMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {127 if len(runes) < len(pattern) {128 return -1, -1129 }130131 for index, r := range pattern {132 char := (*runes)[index]132 char := runes[index]133 if !caseSensitive {134 char = unicode.ToLower(char)135 }136 if char != r {
3 unmodified lines
140 return 0, len(pattern)141}142143// SuffixMatch performs suffix-match144func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {144func SuffixMatch(caseSensitive bool, input []rune, pattern []rune) (int, int) {145 runes := util.TrimRight(input)146 trimmedLen := len(runes)147 diff := trimmedLen - len(pattern)148 if diff < 0 {
11 unmodified lines
160 }161 return trimmedLen - len(pattern), trimmedLen162}163164func EqualMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {165 if len(*runes) != len(pattern) {164func EqualMatch(caseSensitive bool, runes []rune, pattern []rune) (int, int) {165 if len(runes) != len(pattern) {166 return -1, -1167 }168 runesStr := string(*runes)168 runesStr := string(runes)169 if !caseSensitive {170 runesStr = strings.ToLower(runesStr)171 }172 if runesStr == string(pattern) {
4 unmodified lines
modified:src/util/util.go+4 added-4 removed
76 unmodified lines
77func IsTty() bool {78 return int(C.isatty(C.int(os.Stdin.Fd()))) != 079}8081func TrimRight(runes *[]rune) []rune {81func TrimRight(runes []rune) []rune {82 var i int83 for i = len(*runes) - 1; i >= 0; i-- {84 char := (*runes)[i]83 for i = len(runes) - 1; i >= 0; i-- {84 char := runes[i]85 if char != ' ' && char != '\t' {86 break87 }88 }89 return (*runes)[0 : i+1]89 return runes[0 : i+1]90}
modified:src/ansi_test.go+2 added-2 removed
15 unmodified lines
16 src := "hello world"17 var state *ansiState18 clean := "\x1b[0m"19 check := func(assertion func(ansiOffsets []ansiOffset, state *ansiState)) {20 output, ansiOffsets, newState := extractColor(&src, state)20 output, ansiOffsets, newState := extractColor(src, state)21 state = newState22 if *output != "hello world" {22 if output != "hello world" {23 t.Errorf("Invalid output: {}", output)24 }25 fmt.Println(src, ansiOffsets, clean)26 assertion(ansiOffsets, state)
126 unmodified lines
modified:src/ansi.go+6 added-7 removed
34 unmodified lines
35func init() {36 ansiRegex = regexp.MustCompile("\x1b\\[[0-9;]*[mK]")37}3839func extractColor(str *string, state *ansiState) (*string, []ansiOffset, *ansiState) {39func extractColor(str string, state *ansiState) (string, []ansiOffset, *ansiState) {40 var offsets []ansiOffset41 var output bytes.Buffer4243 if state != nil {44 offsets = append(offsets, ansiOffset{[2]int32{0, 0}, *state})45 }4647 idx := 048 for _, offset := range ansiRegex.FindAllStringIndex(*str, -1) {49 output.WriteString((*str)[idx:offset[0]])50 newState := interpretCode((*str)[offset[0]:offset[1]], state)48 for _, offset := range ansiRegex.FindAllStringIndex(str, -1) {49 output.WriteString(str[idx:offset[0]])50 newState := interpretCode(str[offset[0]:offset[1]], state)5152 if !newState.equals(state) {53 if state != nil {54 // Update last offset
13 unmodified lines
6869 idx = offset[1]70 }7172 rest := (*str)[idx:]72 rest := str[idx:]73 if len(rest) > 0 {74 output.WriteString(rest)75 if state != nil {76 // Update last offset77 (&offsets[len(offsets)-1]).offset[1] = int32(utf8.RuneCount(output.Bytes()))78 }79 }80 outputStr := output.String()81 return &outputStr, offsets, state80 return output.String(), offsets, state81}8283func interpretCode(ansiCode string, prevState *ansiState) *ansiState {84 // State
65 unmodified lines
modified:src/chunklist_test.go+8 added-8 removed
4 unmodified lines
5 "testing"6)78func TestChunkList(t *testing.T) {9 cl := NewChunkList(func(s *string, i int) *Item {9 cl := NewChunkList(func(s []rune, i int) *Item {10 return &Item{text: s, rank: Rank{0, 0, uint32(i * 2)}}11 })1213 // Snapshot
2 unmodified lines
16 t.Error("Snapshot should be empty now")17 }1819 // Add some data20 cl.Push("hello")21 cl.Push("world")20 cl.Push([]rune("hello"))21 cl.Push([]rune("world"))2223 // Previously created snapshot should remain the same24 if len(snapshot) > 0 {25 t.Error("Snapshot should not have changed")
9 unmodified lines
35 chunk1 := snapshot[0]36 if len(*chunk1) != 2 {37 t.Error("Snapshot should contain only two items")38 }39 if *(*chunk1)[0].text != "hello" || (*chunk1)[0].rank.index != 0 ||40 *(*chunk1)[1].text != "world" || (*chunk1)[1].rank.index != 2 {39 if string((*chunk1)[0].text) != "hello" || (*chunk1)[0].rank.index != 0 ||40 string((*chunk1)[1].text) != "world" || (*chunk1)[1].rank.index != 2 {41 t.Error("Invalid data")42 }43 if chunk1.IsFull() {44 t.Error("Chunk should not have been marked full yet")45 }4647 // Add more data48 for i := 0; i < chunkSize*2; i++ {49 cl.Push(fmt.Sprintf("item %d", i))49 cl.Push([]rune(fmt.Sprintf("item %d", i)))50 }5152 // Previous snapshot should remain the same53 if len(snapshot) != 1 {
9 unmodified lines
63 if len(*snapshot[2]) != 2 {64 t.Error("Unexpected number of items")65 }6667 cl.Push("hello")68 cl.Push("world")67 cl.Push([]rune("hello"))68 cl.Push([]rune("world"))6970 lastChunkCount := len(*snapshot[len(snapshot)-1])71 if lastChunkCount != 2 {72 t.Error("Unexpected number of items:", lastChunkCount)
2 unmodified lines
modified:src/chunklist.go+4 added-4 removed
5 unmodified lines
6type Chunk []*Item // >>> []Item78// ItemBuilder is a closure type that builds Item object from a pointer to a9// string and an integer10type ItemBuilder func(*string, int) *Item10type ItemBuilder func([]rune, int) *Item1112// ChunkList is a list of Chunks13type ChunkList struct {14 chunks []*Chunk
10 unmodified lines
25 mutex: sync.Mutex{},26 trans: trans}27}2829func (c *Chunk) push(trans ItemBuilder, data *string, index int) bool {29func (c *Chunk) push(trans ItemBuilder, data []rune, index int) bool {30 item := trans(data, index)31 if item != nil {32 *c = append(*c, item)33 return true
18 unmodified lines
52 return chunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))53}5455// Push adds the item to the list56func (cl *ChunkList) Push(data string) bool {56func (cl *ChunkList) Push(data []rune) bool {57 cl.mutex.Lock()58 defer cl.mutex.Unlock()5960 if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {61 newChunk := Chunk(make([]*Item, 0, chunkSize))62 cl.chunks = append(cl.chunks, &newChunk)63 }6465 if cl.lastChunk().push(cl.trans, &data, cl.count) {65 if cl.lastChunk().push(cl.trans, data, cl.count) {66 cl.count++67 return true68 }69 return false
24 unmodified lines
modified:src/core.go+18 added-18 removed
61 unmodified lines
62 // Event channel63 eventBox := util.NewEventBox()6465 // ANSI code processor66 ansiProcessor := func(data *string) (*string, []ansiOffset) {66 ansiProcessor := func(runes []rune) ([]rune, []ansiOffset) {67 // By default, we do nothing68 return data, nil68 return runes, nil69 }70 if opts.Ansi {71 if opts.Theme != nil {72 var state *ansiState73 ansiProcessor = func(data *string) (*string, []ansiOffset) {74 trimmed, offsets, newState := extractColor(data, state)73 ansiProcessor = func(runes []rune) ([]rune, []ansiOffset) {74 trimmed, offsets, newState := extractColor(string(runes), state)75 state = newState76 return trimmed, offsets76 return []rune(trimmed), offsets77 }78 } else {79 // When color is disabled but ansi option is given,80 // we simply strip out ANSI codes from the input81 ansiProcessor = func(data *string) (*string, []ansiOffset) {82 trimmed, _, _ := extractColor(data, nil)83 return trimmed, nil81 ansiProcessor = func(runes []rune) ([]rune, []ansiOffset) {82 trimmed, _, _ := extractColor(string(runes), nil)83 return []rune(trimmed), nil84 }85 }86 }8788 // Chunk list89 var chunkList *ChunkList90 header := make([]string, 0, opts.HeaderLines)91 if len(opts.WithNth) == 0 {92 chunkList = NewChunkList(func(data *string, index int) *Item {92 chunkList = NewChunkList(func(data []rune, index int) *Item {93 if len(header) < opts.HeaderLines {94 header = append(header, *data)94 header = append(header, string(data))95 eventBox.Set(EvtHeader, header)96 return nil97 }98 data, colors := ansiProcessor(data)
3 unmodified lines
102 colors: colors,103 rank: Rank{0, 0, uint32(index)}}104 })105 } else {106 chunkList = NewChunkList(func(data *string, index int) *Item {106 chunkList = NewChunkList(func(data []rune, index int) *Item {107 tokens := Tokenize(data, opts.Delimiter)108 trans := Transform(tokens, opts.WithNth)109 if len(header) < opts.HeaderLines {110 header = append(header, *joinTokens(trans))110 header = append(header, string(joinTokens(trans)))111 eventBox.Set(EvtHeader, header)112 return nil113 }114 item := Item{115 text: joinTokens(trans),116 origText: data,116 origText: &data,117 index: uint32(index),118 colors: nil,119 rank: Rank{0, 0, uint32(index)}}120
6 unmodified lines
127128 // Reader129 streamingFilter := opts.Filter != nil && !sort && !opts.Tac && !opts.Sync130 if !streamingFilter {131 reader := Reader{func(str string) bool {132 return chunkList.Push(str)131 reader := Reader{func(data []rune) bool {132 return chunkList.Push(data)133 }, eventBox, opts.ReadZero}134 go reader.ReadSource()135 }136
13 unmodified lines
150 pattern := patternBuilder([]rune(*opts.Filter))151152 if streamingFilter {153 reader := Reader{154 func(str string) bool {155 item := chunkList.trans(&str, 0)154 func(runes []rune) bool {155 item := chunkList.trans(runes, 0)156 if item != nil && pattern.MatchItem(item) {157 fmt.Println(*item.text)157 fmt.Println(string(item.text))158 }159 return false160 }, eventBox, opts.ReadZero}161 reader.ReadSource()
106 unmodified lines
modified:src/item_test.go+7 added-7 removed
37 unmodified lines
38}3940// Match length, string length, index41func TestItemRank(t *testing.T) {42 strs := []string{"foo", "foobar", "bar", "baz"}43 item1 := Item{text: &strs[0], index: 1, offsets: []Offset{}}42 strs := [][]rune{[]rune("foo"), []rune("foobar"), []rune("bar"), []rune("baz")}43 item1 := Item{text: strs[0], index: 1, offsets: []Offset{}}44 rank1 := item1.Rank(true)45 if rank1.matchlen != 0 || rank1.tiebreak != 3 || rank1.index != 1 {46 t.Error(item1.Rank(true))47 }48 // Only differ in index49 item2 := Item{text: &strs[0], index: 0, offsets: []Offset{}}49 item2 := Item{text: strs[0], index: 0, offsets: []Offset{}}5051 items := []*Item{&item1, &item2}52 sort.Sort(ByRelevance(items))53 if items[0] != &item2 || items[1] != &item1 {
7 unmodified lines
61 t.Error(items)62 }6364 // Sort by relevance65 item3 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}66 item4 := Item{text: &strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}67 item5 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}68 item6 := Item{text: &strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}65 item3 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}66 item4 := Item{text: strs[1], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}67 item5 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 3}, Offset{5, 7}}}68 item6 := Item{text: strs[2], rank: Rank{0, 0, 2}, offsets: []Offset{Offset{1, 2}, Offset{6, 7}}}69 items = []*Item{&item1, &item2, &item3, &item4, &item5, &item6}70 sort.Sort(ByRelevance(items))71 if items[0] != &item2 || items[1] != &item1 ||72 items[2] != &item6 || items[3] != &item4 ||
32 unmodified lines
modified:src/item.go+11 added-9 removed
15 unmodified lines
16}1718// Item represents each input line19type Item struct {20 text *string21 origText *string22 transformed *[]Token20 text []rune21 origText *[]rune22 transformed []Token23 index uint3224 offsets []Offset25 colors []ansiOffset26 rank Rank
38 unmodified lines
65 case byLength:66 // It is guaranteed that .transformed in not null in normal execution67 if i.transformed != nil {68 lenSum := 069 for _, token := range *i.transformed {70 lenSum += len(*token.text)69 for _, token := range i.transformed {70 lenSum += len(token.text)71 }72 tiebreak = uint16(lenSum)73 } else {74 tiebreak = uint16(len(*i.text))74 tiebreak = uint16(len(i.text))75 }76 case byBegin:77 // We can't just look at i.offsets[0][0] because it can be an inverse term78 tiebreak = uint16(minBegin)79 case byEnd:80 if prevEnd > 0 {81 tiebreak = uint16(1 + len(*i.text) - prevEnd)81 tiebreak = uint16(1 + len(i.text) - prevEnd)82 } else {83 // Empty offsets due to inverse terms.84 tiebreak = 185 }
13 unmodified lines
99}100101// StringPtr returns the pointer to the original string102func (i *Item) StringPtr() *string {103 runes := i.text104 if i.origText != nil {104 return i.origText105 runes = *i.origText106 }106 return i.text107 str := string(runes)108 return &str109}110111func (item *Item) colorOffsets(color int, bold bool, current bool) []colorOffset {112 if len(item.colors) == 0 {
151 unmodified lines
modified:src/merger_test.go+1 added-1 removed
20 unmodified lines
21 eidx := sidx + int32(rand.Uint32()%20)22 offsets[idx] = Offset{sidx, eidx}23 }24 return &Item{25 text: &str,25 text: []rune(str),26 index: rand.Uint32(),27 offsets: offsets}28}29
64 unmodified lines
modified:src/pattern_test.go+11 added-12 removed
1package fzf23import (4 "reflect"5 "testing"67 "github.com/junegunn/fzf/src/algo"8)
50 unmodified lines
59 defer clearPatternCache()60 clearPatternCache()61 pattern := BuildPattern(ModeExtended, CaseSmart,62 []Range{}, nil, []rune("'abc"))62 runes := []rune("aabbcc abc")63 sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)63 sidx, eidx := algo.ExactMatchNaive(64 pattern.caseSensitive, []rune("aabbcc abc"), pattern.terms[0].text)65 if sidx != 7 || eidx != 10 {66 t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)67 }68}
3 unmodified lines
72 clearPatternCache()73 pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("^AbC$"))7475 match := func(str string, sidxExpected int, eidxExpected int) {75 runes := []rune(str)76 sidx, eidx := algo.EqualMatch(pattern.caseSensitive, &runes, pattern.terms[0].text)76 sidx, eidx := algo.EqualMatch(77 pattern.caseSensitive, []rune(str), pattern.terms[0].text)78 if sidx != sidxExpected || eidx != eidxExpected {79 t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)80 }81 }
26 unmodified lines
108 }109}110111func TestOrigTextAndTransformed(t *testing.T) {111 strptr := func(str string) *string {112 return &str113 }112 pattern := BuildPattern(ModeExtended, CaseSmart, []Range{}, nil, []rune("jg"))115 tokens := Tokenize(strptr("junegunn"), nil)113 tokens := Tokenize([]rune("junegunn"), nil)114 trans := Transform(tokens, []Range{Range{1, 1}})115116 origRunes := []rune("junegunn.choi")117 for _, mode := range []Mode{ModeFuzzy, ModeExtended} {118 chunk := Chunk{119 &Item{121 text: strptr("junegunn"),122 origText: strptr("junegunn.choi"),120 text: []rune("junegunn"),121 origText: &origRunes,122 transformed: trans},123 }124 pattern.mode = mode125 matches := pattern.matchChunk(&chunk)127 if *matches[0].text != "junegunn" || *matches[0].origText != "junegunn.choi" ||126 if string(matches[0].text) != "junegunn" || string(*matches[0].origText) != "junegunn.choi" ||127 matches[0].offsets[0][0] != 0 || matches[0].offsets[0][1] != 5 ||129 matches[0].transformed != trans {128 !reflect.DeepEqual(matches[0].transformed, trans) {129 t.Error("Invalid match result", matches)130 }131 }132}
modified:src/pattern.go+8 added-10 removed
42 unmodified lines
43 terms []term44 hasInvTerm bool45 delimiter *regexp.Regexp46 nth []Range47 procFun map[termType]func(bool, *[]rune, []rune) (int, int)47 procFun map[termType]func(bool, []rune, []rune) (int, int)48}4950var (51 _patternCache map[string]*Pattern
61 unmodified lines
113 terms: terms,114 hasInvTerm: hasInvTerm,115 nth: nth,116 delimiter: delimiter,117 procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}117 procFun: make(map[termType]func(bool, []rune, []rune) (int, int))}118119 ptr.procFun[termFuzzy] = algo.FuzzyMatch120 ptr.procFun[termEqual] = algo.EqualMatch121 ptr.procFun[termExact] = algo.ExactMatchNaive
182 unmodified lines
304 }305 return offsets306}307308func (p *Pattern) prepareInput(item *Item) *[]Token {308func (p *Pattern) prepareInput(item *Item) []Token {309 if item.transformed != nil {310 return item.transformed311 }312313 var ret *[]Token313 var ret []Token314 if len(p.nth) > 0 {315 tokens := Tokenize(item.text, p.delimiter)316 ret = Transform(tokens, p.nth)317 } else {318 runes := []rune(*item.text)319 trans := []Token{Token{text: &runes, prefixLength: 0}}320 ret = &trans318 ret = []Token{Token{text: item.text, prefixLength: 0}}319 }320 item.transformed = ret321 return ret322}323326func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),327 tokens *[]Token, caseSensitive bool, pattern []rune) (int, int) {328 for _, part := range *tokens {324func (p *Pattern) iter(pfun func(bool, []rune, []rune) (int, int),325 tokens []Token, caseSensitive bool, pattern []rune) (int, int) {326 for _, part := range tokens {327 prefixLength := part.prefixLength328 if sidx, eidx := pfun(caseSensitive, part.text, pattern); sidx >= 0 {329 return sidx + prefixLength, eidx + prefixLength330 }
3 unmodified lines
modified:src/reader_test.go+1 added-1 removed
8 unmodified lines
9func TestReadFromCommand(t *testing.T) {10 strs := []string{}11 eb := util.NewEventBox()12 reader := Reader{13 pusher: func(s string) bool { strs = append(strs, s); return true },13 pusher: func(s []rune) bool { strs = append(strs, string(s)); return true },14 eventBox: eb}1516 // Check EventBox17 if eb.Peek(EvtReadNew) {
39 unmodified lines
modified:src/reader.go+19 added-6 removed
3 unmodified lines
4 "bufio"5 "io"6 "os"7 "os/exec"8 "unicode/utf8"910 "github.com/junegunn/fzf/src/util"11)1213// Reader reads from command or standard input14type Reader struct {14 pusher func(string) bool15 pusher func([]rune) bool16 eventBox *util.EventBox17 delimNil bool18}19
17 unmodified lines
37 delim = '\000'38 }39 reader := bufio.NewReader(src)40 for {40 line, err := reader.ReadString(delim)41 if line != "" {42 // "ReadString returns err != nil if and only if the returned data does not end in delim."41 // ReadBytes returns err != nil if and only if the returned data does not42 // end in delim.43 bytea, err := reader.ReadBytes(delim)44 if len(bytea) > 0 {45 runes := make([]rune, 0, len(bytea))46 for i := 0; i < len(bytea); {47 if bytea[i] < utf8.RuneSelf {48 runes = append(runes, rune(bytea[i]))49 i++50 } else {51 r, sz := utf8.DecodeRune(bytea[i:])52 i += sz53 runes = append(runes, r)54 }55 }56 if err == nil {44 line = line[:len(line)-1]57 runes = runes[:len(runes)-1]58 }46 if r.pusher(line) {59 if r.pusher(runes) {60 r.eventBox.Set(EvtReadNew, nil)61 }62 }63 if err != nil {
22 unmodified lines
modified:src/terminal.go+3 added-3 removed
439 unmodified lines
440 }441 if line >= max {442 continue443 }444 trimmed, colors, newState := extractColor(&lineStr, state)444 trimmed, colors, newState := extractColor(lineStr, state)445 state = newState446 item := &Item{447 text: trimmed,447 text: []rune(trimmed),448 index: 0,449 colors: colors,450 rank: Rank{0, 0, 0}}451
84 unmodified lines
536 }537 }538539 // Overflow540 text := []rune(*item.text)540 text := item.text541 offsets := item.colorOffsets(col2, bold, current)542 maxWidth := C.MaxX() - 3 - t.marginInt[1] - t.marginInt[3]543 fullWidth := displayWidth(text)544 if fullWidth > maxWidth {
561 unmodified lines
modified:src/tokenizer_test.go+22 added-22 removed
41 unmodified lines
4243func TestTokenize(t *testing.T) {44 // AWK-style45 input := " abc: def: ghi "46 tokens := Tokenize(&input, nil)47 if string(*tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {46 tokens := Tokenize([]rune(input), nil)47 if string(tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {48 t.Errorf("%s", tokens)49 }5051 // With delimiter52 tokens = Tokenize(&input, delimiterRegexp(":"))53 if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {52 tokens = Tokenize([]rune(input), delimiterRegexp(":"))53 if string(tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {54 t.Errorf("%s", tokens)55 }56}5758func TestTransform(t *testing.T) {59 input := " abc: def: ghi: jkl"60 {61 tokens := Tokenize(&input, nil)61 tokens := Tokenize([]rune(input), nil)62 {63 ranges := splitNth("1,2,3")64 tx := Transform(tokens, ranges)65 if *joinTokens(tx) != "abc: def: ghi: " {66 t.Errorf("%s", *tx)65 if string(joinTokens(tx)) != "abc: def: ghi: " {66 t.Errorf("%s", tx)67 }68 }69 {70 ranges := splitNth("1..2,3,2..,1")71 tx := Transform(tokens, ranges)72 if *joinTokens(tx) != "abc: def: ghi: def: ghi: jklabc: " ||73 len(*tx) != 4 ||74 string(*(*tx)[0].text) != "abc: def: " || (*tx)[0].prefixLength != 2 ||75 string(*(*tx)[1].text) != "ghi: " || (*tx)[1].prefixLength != 14 ||76 string(*(*tx)[2].text) != "def: ghi: jkl" || (*tx)[2].prefixLength != 8 ||77 string(*(*tx)[3].text) != "abc: " || (*tx)[3].prefixLength != 2 {78 t.Errorf("%s", *tx)72 if string(joinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||73 len(tx) != 4 ||74 string(tx[0].text) != "abc: def: " || tx[0].prefixLength != 2 ||75 string(tx[1].text) != "ghi: " || tx[1].prefixLength != 14 ||76 string(tx[2].text) != "def: ghi: jkl" || tx[2].prefixLength != 8 ||77 string(tx[3].text) != "abc: " || tx[3].prefixLength != 2 {78 t.Errorf("%s", tx)79 }80 }81 }82 {83 tokens := Tokenize(&input, delimiterRegexp(":"))83 tokens := Tokenize([]rune(input), delimiterRegexp(":"))84 {85 ranges := splitNth("1..2,3,2..,1")86 tx := Transform(tokens, ranges)87 if *joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||88 len(*tx) != 4 ||89 string(*(*tx)[0].text) != " abc: def:" || (*tx)[0].prefixLength != 0 ||90 string(*(*tx)[1].text) != " ghi:" || (*tx)[1].prefixLength != 12 ||91 string(*(*tx)[2].text) != " def: ghi: jkl" || (*tx)[2].prefixLength != 6 ||92 string(*(*tx)[3].text) != " abc:" || (*tx)[3].prefixLength != 0 {93 t.Errorf("%s", *tx)87 if string(joinTokens(tx)) != " abc: def: ghi: def: ghi: jkl abc:" ||88 len(tx) != 4 ||89 string(tx[0].text) != " abc: def:" || tx[0].prefixLength != 0 ||90 string(tx[1].text) != " ghi:" || tx[1].prefixLength != 12 ||91 string(tx[2].text) != " def: ghi: jkl" || tx[2].prefixLength != 6 ||92 string(tx[3].text) != " abc:" || tx[3].prefixLength != 0 {93 t.Errorf("%s", tx)94 }95 }96 }97}
4 unmodified lines
modified:src/tokenizer.go+22 added-23 removed
16 unmodified lines
17}1819// Token contains the tokenized part of the strings and its prefix length20type Token struct {21 text *[]rune21 text []rune22 prefixLength int23}2425func newRange(begin int, end int) Range {
48 unmodified lines
74 prefixLength := begin75 for idx, token := range tokens {76 // Need to define a new local variable instead of the reused token to take77 // the pointer to it78 runes := []rune(token)79 ret[idx] = Token{text: &runes, prefixLength: prefixLength}78 ret[idx] = Token{text: []rune(token), prefixLength: prefixLength}79 prefixLength += len([]rune(token))80 }81 return ret82}
3 unmodified lines
86 awkBlack87 awkWhite88)8991func awkTokenizer(input *string) ([]string, int) {90func awkTokenizer(input []rune) ([]string, int) {91 // 9, 3292 ret := []string{}93 str := []rune{}94 prefixLength := 095 state := awkNil97 for _, r := range []rune(*input) {96 for _, r := range input {97 white := r == 9 || r == 3298 switch state {99 case awkNil:100 if white {
23 unmodified lines
124 return ret, prefixLength125}126127// Tokenize tokenizes the given string with the delimiter129func Tokenize(str *string, delimiter *regexp.Regexp) []Token {128func Tokenize(runes []rune, delimiter *regexp.Regexp) []Token {129 if delimiter == nil {130 // AWK-style (\S+\s*)132 tokens, prefixLength := awkTokenizer(str)131 tokens, prefixLength := awkTokenizer(runes)132 return withPrefixLengths(tokens, prefixLength)133 }135 tokens := delimiter.FindAllString(*str, -1)134 tokens := delimiter.FindAllString(string(runes), -1)135 return withPrefixLengths(tokens, 0)136}137139func joinTokens(tokens *[]Token) *string {140 ret := ""141 for _, token := range *tokens {142 ret += string(*token.text)138func joinTokens(tokens []Token) []rune {139 ret := []rune{}140 for _, token := range tokens {141 ret = append(ret, token.text...)142 }144 return &ret143 return ret144}145147func joinTokensAsRunes(tokens *[]Token) *[]rune {146func joinTokensAsRunes(tokens []Token) []rune {147 ret := []rune{}149 for _, token := range *tokens {150 ret = append(ret, *token.text...)148 for _, token := range tokens {149 ret = append(ret, token.text...)150 }152 return &ret151 return ret152}153154// Transform is used to transform the input when --with-nth option is given156func Transform(tokens []Token, withNth []Range) *[]Token {155func Transform(tokens []Token, withNth []Range) []Token {156 transTokens := make([]Token, len(withNth))157 numTokens := len(tokens)158 for idx, r := range withNth {159 part := []rune{}160 minIdx := 0161 if r.begin == r.end {162 idx := r.begin163 if idx == rangeEllipsis {165 part = append(part, *joinTokensAsRunes(&tokens)...)164 part = append(part, joinTokensAsRunes(tokens)...)165 } else {166 if idx < 0 {167 idx += numTokens + 1168 }169 if idx >= 1 && idx <= numTokens {170 minIdx = idx - 1172 part = append(part, *tokens[idx-1].text...)171 part = append(part, tokens[idx-1].text...)172 }173 }174 } else {175 var begin, end int
18 unmodified lines
194 }195 minIdx = util.Max(0, begin-1)196 for idx := begin; idx <= end; idx++ {197 if idx >= 1 && idx <= numTokens {199 part = append(part, *tokens[idx-1].text...)198 part = append(part, tokens[idx-1].text...)199 }200 }201 }202 var prefixLength int
1 unmodified line
204 prefixLength = tokens[minIdx].prefixLength205 } else {206 prefixLength = 0207 }209 transTokens[idx] = Token{&part, prefixLength}208 transTokens[idx] = Token{part, prefixLength}209 }211 return &transTokens210 return transTokens211}