Skip to content
Myr

Improvements in performance and memory usage

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

I profiled fzf and it turned out that it was spending significant amount of time repeatedly converting character arrays into Unicode codepoints. This commit greatly improves search performance after the initial scan by memoizing the converted results. This commit also addresses the problem of unbounded memory usage of fzf. fzf is a short-lived process that usually processes small input, so it was implemented to cache the intermediate results very aggressively with no notion of cache expiration/eviction. I still think a proper implementation of caching scheme is definitely an overkill. Instead this commit introduces limits to the maximum size (or minimum selectivity) of the intermediate results that can be cached.

authored by Junegunn Choi · committed by Junegunn Choi · parent 288131a · Browse files · 19 files+144 added−135 removed
This commit

State

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

Diff stats

19 files+144 added−135 removed

  • other:+144 added−135 removed

19 files+144 added−135 removed

modified:src/algo/algo_test.go+3 added-3 removed
3 unmodified lines
4 "strings"5 "testing"6)78func assertMatch(t *testing.T, fun func(bool, *string, []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)12 s, e := fun(caseSensitive, &input, []rune(pattern))13 s, e := fun(caseSensitive, &runes, []rune(pattern))14 if s != sidx {15 t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)16 }17 if e != eidx {
27 unmodified lines
45}4647func TestEmptyPattern(t *testing.T) {48 assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)48 assertMatch(t, ExactMatchStrings, true, "foobar", "", 0, 0)49 assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)50 assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)51 assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)52}
modified:src/algo/algo.go+15 added-39 removed
1package algo23import (4 "strings"4 "unicode"56 "github.com/junegunn/fzf/src/util"7)89/*10 * String matching algorithms here do not use strings.ToLower to avoid
3 unmodified lines
14 * In short: They try to do as little work as possible.15 */1617// FuzzyMatch performs fuzzy-match17func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {18func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {19 if len(pattern) == 0 {20 return 0, 021 }2222 runes := []rune(*input)2323 // 0. (FIXME) How to find the shortest match?24 // a_____b__c__abc25 // ^^^^^^^^^^ ^^^26 // 1. forward scan (abc)
5 unmodified lines
32 pidx := 033 sidx := -134 eidx := -13537 for index, char := range runes {36 for index, char := range *runes {37 // This is considerably faster than blindly applying strings.ToLower to the38 // whole string39 if !caseSensitive {40 // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable41 // difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go42 // compiler as of now does not inline non-leaf functions.)43 if char >= 'A' && char <= 'Z' {44 char += 3246 runes[index] = char45 (*runes)[index] = char46 } else if char > unicode.MaxASCII {47 char = unicode.To(unicode.LowerCase, char)49 runes[index] = char48 (*runes)[index] = char49 }50 }51 if char == pattern[pidx] {52 if sidx < 0 {
8 unmodified lines
6162 if sidx >= 0 && eidx >= 0 {63 pidx--64 for index := eidx - 1; index >= sidx; index-- {66 char := runes[index]65 char := (*runes)[index]66 if char == pattern[pidx] {67 if pidx--; pidx < 0 {68 sidx = index69 break
4 unmodified lines
74 }75 return -1, -176}7779// ExactMatchStrings performs exact-match using strings package.80// Currently not used.81func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {82 if len(pattern) == 0 {83 return 0, 084 }8586 var str string87 if caseSensitive {88 str = *input89 } else {90 str = strings.ToLower(*input)91 }9293 if idx := strings.Index(str, string(pattern)); idx >= 0 {94 prefixRuneLen := len([]rune((*input)[:idx]))95 return prefixRuneLen, prefixRuneLen + len(pattern)96 }97 return -1, -198}9978// ExactMatchNaive is a basic string searching algorithm that handles case79// sensitivity. Although naive, it still performs better than the combination80// of strings.ToLower + strings.Index for typical fzf use cases where input81// strings and patterns are not very long.82//83// We might try to implement better algorithms in the future:84// http://en.wikipedia.org/wiki/String_searching_algorithm107func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, int) {85func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {86 if len(pattern) == 0 {87 return 0, 088 }89112 runes := []rune(*input)113 numRunes := len(runes)90 numRunes := len(*runes)91 plen := len(pattern)92 if numRunes < plen {93 return -1, -194 }9596 pidx := 097 for index := 0; index < numRunes; index++ {121 char := runes[index]98 char := (*runes)[index]99 if !caseSensitive {100 if char >= 'A' && char <= 'Z' {101 char += 32102 } else if char > unicode.MaxASCII {
13 unmodified lines
116 return -1, -1117}118119// PrefixMatch performs prefix-match143func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {144 runes := []rune(*input)145 if len(runes) < len(pattern) {120func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {121 if len(*runes) < len(pattern) {122 return -1, -1123 }124125 for index, r := range pattern {150 char := runes[index]126 char := (*runes)[index]127 if !caseSensitive {128 char = unicode.ToLower(char)129 }130 if char != r {
3 unmodified lines
134 return 0, len(pattern)135}136137// SuffixMatch performs suffix-match162func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {163 runes := []rune(strings.TrimRight(*input, " "))138func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {139 runes := util.TrimRight(input)140 trimmedLen := len(runes)141 diff := trimmedLen - len(pattern)142 if diff < 0 {143 return -1, -1
13 unmodified lines
modified:src/util/util.go+11 added
75 unmodified lines
76// IsTty returns true is stdin is a terminal77func IsTty() bool {78 return int(C.isatty(C.int(os.Stdin.Fd()))) != 079}8081func TrimRight(runes *[]rune) []rune {82 var i int83 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]90}
modified:src/cache_test.go+1 added-1 removed
2 unmodified lines
3import "testing"45func TestChunkCache(t *testing.T) {6 cache := NewChunkCache()7 chunk2 := make(Chunk, ChunkSize)7 chunk2 := make(Chunk, chunkSize)8 chunk1p := &Chunk{}9 chunk2p := &chunk210 items1 := []*Item{&Item{}}11 items2 := []*Item{&Item{}, &Item{}}
29 unmodified lines
modified:src/cache.go+6 added-6 removed
1package fzf23import "sync"45// QueryCache associates strings to lists of items6type QueryCache map[string][]*Item5// queryCache associates strings to lists of items6type queryCache map[string][]*Item78// ChunkCache associates Chunk and query string to lists of items9type ChunkCache struct {10 mutex sync.Mutex11 cache map[*Chunk]*QueryCache11 cache map[*Chunk]*queryCache12}1314// NewChunkCache returns a new ChunkCache15func NewChunkCache() ChunkCache {16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*QueryCache)}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 []*Item) {21 if len(key) == 0 || !chunk.IsFull() {21 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {22 return23 }2425 cc.mutex.Lock()26 defer cc.mutex.Unlock()2728 qc, ok := cc.cache[chunk]29 if !ok {30 cc.cache[chunk] = &QueryCache{}30 cc.cache[chunk] = &queryCache{}31 qc = cc.cache[chunk]32 }33 (*qc)[key] = list34}
19 unmodified lines
modified:src/chunklist_test.go+2 added-2 removed
43 unmodified lines
44 t.Error("Chunk should not have been marked full yet")45 }4647 // Add more data48 for i := 0; i < ChunkSize*2; i++ {48 for i := 0; i < chunkSize*2; i++ {49 cl.Push(fmt.Sprintf("item %d", i))50 }5152 // Previous snapshot should remain the same
3 unmodified lines
5657 // New snapshot58 snapshot, count = cl.Snapshot()59 if len(snapshot) != 3 || !snapshot[0].IsFull() ||60 !snapshot[1].IsFull() || snapshot[2].IsFull() || count != ChunkSize*2+2 {60 !snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {61 t.Error("Expected two full chunks and one more chunk")62 }63 if len(*snapshot[2]) != 2 {64 t.Error("Unexpected number of items")
10 unmodified lines
modified:src/chunklist.go+4 added-7 removed
1package fzf23import "sync"45// Capacity of each chunk6const ChunkSize int = 10078// Chunk is a list of Item pointers whose size has the upper limit of ChunkSize5// Chunk is a list of Item pointers whose size has the upper limit of chunkSize6type Chunk []*Item // >>> []Item78// ItemBuilder is a closure type that builds Item object from a pointer to a9// string and an integer
21 unmodified lines
31}3233// IsFull returns true if the Chunk is full34func (c *Chunk) IsFull() bool {38 return len(*c) == ChunkSize35 return len(*c) == chunkSize36}3738func (cl *ChunkList) lastChunk() *Chunk {39 return cl.chunks[len(cl.chunks)-1]
3 unmodified lines
43func CountItems(cs []*Chunk) int {44 if len(cs) == 0 {45 return 046 }50 return ChunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))47 return chunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))48}4950// Push adds the item to the list51func (cl *ChunkList) Push(data string) {52 cl.mutex.Lock()53 defer cl.mutex.Unlock()5455 if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {59 newChunk := Chunk(make([]*Item, 0, ChunkSize))56 newChunk := Chunk(make([]*Item, 0, chunkSize))57 cl.chunks = append(cl.chunks, &newChunk)58 }5960 cl.lastChunk().push(cl.trans, &data, cl.count)
25 unmodified lines
modified:src/constants.go+29 added-2 removed
1package fzf23import (4 "time"56 "github.com/junegunn/fzf/src/util"7)89const (7// Current version8const Version = "0.9.9"10 // Current version11 Version = "0.9.9"1213 // Core14 coordinatorDelayMax time.Duration = 100 * time.Millisecond15 coordinatorDelayStep time.Duration = 10 * time.Millisecond1617 // Reader18 defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`1920 // Terminal21 initialDelay = 100 * time.Millisecond22 spinnerDuration = 200 * time.Millisecond2324 // Matcher25 progressMinDuration = 200 * time.Millisecond2627 // Capacity of each chunk28 chunkSize int = 1002930 // Do not cache results of low selectivity queries31 queryCacheMax int = chunkSize / 53233 // Not to cache mergers with large lists34 mergerCacheMax int = 10000035)3637// fzf events38const (39 EvtReadNew util.EventType = iota40 EvtReadFin
5 unmodified lines
modified:src/core.go+2 added-4 removed
32 unmodified lines
3334 "github.com/junegunn/fzf/src/util"35)3637const coordinatorDelayMax time.Duration = 100 * time.Millisecond38const coordinatorDelayStep time.Duration = 10 * time.Millisecond3937func initProcs() {38 runtime.GOMAXPROCS(runtime.NumCPU())39}40
54 unmodified lines
95 })96 } else {97 chunkList = NewChunkList(func(data *string, index int) *Item {98 tokens := Tokenize(data, opts.Delimiter)99 trans := Transform(tokens, opts.WithNth)100 item := Item{103 text: Transform(tokens, opts.WithNth).whole,101 text: joinTokens(trans),102 origText: data,103 index: uint32(index),104 colors: nil,105 rank: Rank{0, 0, uint32(index)}}
142 unmodified lines
modified:src/item.go+1 added-1 removed
17 unmodified lines
18// Item represents each input line19type Item struct {20 text *string21 origText *string22 transformed *Transformed22 transformed *[]Token23 index uint3224 offsets []Offset25 colors []ansiOffset26 rank Rank
209 unmodified lines
modified:src/matcher.go+3 added-5 removed
32 unmodified lines
33 reqRetry util.EventType = iota34 reqReset35)3637const (38 progressMinDuration = 200 * time.Millisecond39)4037// NewMatcher returns a new Matcher38func NewMatcher(patternBuilder func([]rune) *Pattern,39 sort bool, tac bool, eventBox *util.EventBox) *Matcher {40 return &Matcher{
54 unmodified lines
95 merger, cancelled = m.scan(request)96 }9798 if !cancelled {99 if merger.Cacheable() {103 m.mergerCache[patternString] = merger100 m.mergerCache[patternString] = merger101 }102 merger.final = request.final103 m.eventBox.Set(EvtSearchFin, merger)104 }105 }
116 unmodified lines
modified:src/merger.go+6 added-2 removed
59 unmodified lines
60 if mg.chunks != nil {61 if mg.tac {62 idx = mg.count - idx - 163 }64 chunk := (*mg.chunks)[idx/ChunkSize]65 return (*chunk)[idx%ChunkSize]64 chunk := (*mg.chunks)[idx/chunkSize]65 return (*chunk)[idx%chunkSize]66 }6768 if mg.sorted {69 return mg.mergedGet(idx)
11 unmodified lines
81 }82 panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))83}8485func (mg *Merger) Cacheable() bool {86 return mg.count < mergerCacheMax87}8889func (mg *Merger) mergedGet(idx int) *Item {90 for i := len(mg.merged); i <= idx; i++ {91 minRank := Rank{0, 0, 0}92 minIdx := -1
26 unmodified lines
modified:src/pattern_test.go+2 added-2 removed
56 unmodified lines
57 defer clearPatternCache()58 clearPatternCache()59 pattern := BuildPattern(ModeExtended, CaseSmart,60 []Range{}, nil, []rune("'abc"))61 str := "aabbcc abc"62 sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &str, pattern.terms[0].text)61 runes := []rune("aabbcc abc")62 sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)63 if sidx != 7 || eidx != 10 {64 t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)65 }66}
50 unmodified lines
modified:src/pattern.go+9 added-10 removed
41 unmodified lines
42 terms []term43 hasInvTerm bool44 delimiter *regexp.Regexp45 nth []Range46 procFun map[termType]func(bool, *string, []rune) (int, int)46 procFun map[termType]func(bool, *[]rune, []rune) (int, int)47}4849var (50 _patternCache map[string]*Pattern
70 unmodified lines
121 terms: terms,122 hasInvTerm: hasInvTerm,123 nth: nth,124 delimiter: delimiter,125 procFun: make(map[termType]func(bool, *string, []rune) (int, int))}125 procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}126127 ptr.procFun[termFuzzy] = algo.FuzzyMatch128 ptr.procFun[termExact] = algo.ExactMatchNaive129 ptr.procFun[termPrefix] = algo.PrefixMatch
169 unmodified lines
299 }300 return offsets301}302303func (p *Pattern) prepareInput(item *Item) *Transformed {303func (p *Pattern) prepareInput(item *Item) *[]Token {304 if item.transformed != nil {305 return item.transformed306 }307308 var ret *Transformed308 var ret *[]Token309 if len(p.nth) > 0 {310 tokens := Tokenize(item.text, p.delimiter)311 ret = Transform(tokens, p.nth)312 } else {313 trans := Transformed{314 whole: item.text,315 parts: []Token{Token{text: item.text, prefixLength: 0}}}313 runes := []rune(*item.text)314 trans := []Token{Token{text: &runes, prefixLength: 0}}315 ret = &trans316 }317 item.transformed = ret318 return ret319}320322func (p *Pattern) iter(pfun func(bool, *string, []rune) (int, int),323 inputs *Transformed, pattern []rune) (int, int) {324 for _, part := range inputs.parts {321func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),322 tokens *[]Token, pattern []rune) (int, int) {323 for _, part := range *tokens {324 prefixLength := part.prefixLength325 if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {326 return sidx + prefixLength, eidx + prefixLength327 }
3 unmodified lines
modified:src/reader.go-2 removed
7 unmodified lines
89 "github.com/junegunn/fzf/src/util"10)1112const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`1312// Reader reads from command or standard input13type Reader struct {14 pusher func(string)15 eventBox *util.EventBox
42 unmodified lines
modified:src/terminal.go+6 added-11 removed
36 unmodified lines
37 count int38 progress int39 reading bool40 merger *Merger41 selected map[*string]selectedItem41 selected map[uint32]selectedItem42 reqBox *util.EventBox43 eventBox *util.EventBox44 mutex sync.Mutex45 initFunc func()
32 unmodified lines
78 reqClose79 reqQuit80)8182const (83 initialDelay = 100 * time.Millisecond84 spinnerDuration = 200 * time.Millisecond85)8682// NewTerminal returns new Terminal object83func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {84 input := []rune(opts.Query)85 return &Terminal{
11 unmodified lines
97 expect: opts.Expect,98 pressed: 0,99 printQuery: opts.PrintQuery,100 merger: EmptyMerger,106 selected: make(map[*string]selectedItem),101 selected: make(map[uint32]selectedItem),102 reqBox: util.NewEventBox(),103 eventBox: eventBox,104 mutex: sync.Mutex{},105 suppress: true,
161 unmodified lines
267 }268}269270func (t *Terminal) printItem(item *Item, current bool) {276 _, selected := t.selected[item.text]271 _, selected := t.selected[item.index]272 if current {273 C.CPrint(C.ColCursor, true, ">")274 if selected {275 C.CPrint(C.ColCurrent, true, ">")
283 unmodified lines
559 }560 toggle := func() {561 if t.cy < t.merger.Length() {562 item := t.merger.Get(t.cy)568 if _, found := t.selected[item.text]; !found {563 if _, found := t.selected[item.index]; !found {564 var strptr *string565 if item.origText != nil {566 strptr = item.origText567 } else {568 strptr = item.text569 }575 t.selected[item.text] = selectedItem{time.Now(), strptr}570 t.selected[item.index] = selectedItem{time.Now(), strptr}571 } else {577 delete(t.selected, item.text)572 delete(t.selected, item.index)573 }574 req(reqInfo)575 }576 }
190 unmodified lines
modified:src/tokenizer_test.go+15 added-15 removed
42 unmodified lines
43func TestTokenize(t *testing.T) {44 // AWK-style45 input := " abc: def: ghi "46 tokens := Tokenize(&input, nil)47 if *tokens[0].text != "abc: " || tokens[0].prefixLength != 2 {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 *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {53 if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {54 t.Errorf("%s", tokens)55 }56}57
3 unmodified lines
61 tokens := Tokenize(&input, nil)62 {63 ranges := splitNth("1,2,3")64 tx := Transform(tokens, ranges)65 if *tx.whole != "abc: def: ghi: " {65 if *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 *tx.whole != "abc: def: ghi: def: ghi: jklabc: " ||73 len(tx.parts) != 4 ||74 *tx.parts[0].text != "abc: def: " || tx.parts[0].prefixLength != 2 ||75 *tx.parts[1].text != "ghi: " || tx.parts[1].prefixLength != 14 ||76 *tx.parts[2].text != "def: ghi: jkl" || tx.parts[2].prefixLength != 8 ||77 *tx.parts[3].text != "abc: " || tx.parts[3].prefixLength != 2 {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)79 }80 }81 }
1 unmodified line
83 tokens := Tokenize(&input, delimiterRegexp(":"))84 {85 ranges := splitNth("1..2,3,2..,1")86 tx := Transform(tokens, ranges)87 if *tx.whole != " abc: def: ghi: def: ghi: jkl abc:" ||88 len(tx.parts) != 4 ||89 *tx.parts[0].text != " abc: def:" || tx.parts[0].prefixLength != 0 ||90 *tx.parts[1].text != " ghi:" || tx.parts[1].prefixLength != 12 ||91 *tx.parts[2].text != " def: ghi: jkl" || tx.parts[2].prefixLength != 6 ||92 *tx.parts[3].text != " abc:" || tx.parts[3].prefixLength != 0 {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)94 }95 }96 }
5 unmodified lines
modified:src/tokenizer.go+21 added-23 removed
14 unmodified lines
15 begin int16 end int17}1819// Transformed holds the result of tokenization and transformation20type Transformed struct {21 whole *string22 parts []Token23}2419// Token contains the tokenized part of the strings and its prefix length20type Token struct {27 text *string21 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 it84 str := token85 ret[idx] = Token{text: &str, prefixLength: prefixLength}78 runes := []rune(token)79 ret[idx] = Token{text: &runes, prefixLength: prefixLength}80 prefixLength += len([]rune(token))81 }82 return ret83}
51 unmodified lines
135 tokens := delimiter.FindAllString(*str, -1)136 return withPrefixLengths(tokens, 0)137}138145func joinTokens(tokens []Token) string {139func joinTokens(tokens *[]Token) *string {140 ret := ""147 for _, token := range tokens {148 ret += *token.text141 for _, token := range *tokens {142 ret += string(*token.text)143 }150 return ret144 return &ret145}146147func joinTokensAsRunes(tokens *[]Token) *[]rune {148 ret := []rune{}149 for _, token := range *tokens {150 ret = append(ret, *token.text...)151 }152 return &ret153}154155// Transform is used to transform the input when --with-nth option is given154func Transform(tokens []Token, withNth []Range) *Transformed {156func Transform(tokens []Token, withNth []Range) *[]Token {157 transTokens := make([]Token, len(withNth))158 numTokens := len(tokens)157 whole := ""159 for idx, r := range withNth {159 part := ""160 part := []rune{}161 minIdx := 0162 if r.begin == r.end {163 idx := r.begin164 if idx == rangeEllipsis {164 part += joinTokens(tokens)165 part = append(part, *joinTokensAsRunes(&tokens)...)166 } else {167 if idx < 0 {168 idx += numTokens + 1169 }170 if idx >= 1 && idx <= numTokens {171 minIdx = idx - 1171 part += *tokens[idx-1].text172 part = append(part, *tokens[idx-1].text...)173 }174 }175 } else {176 var begin, end int
18 unmodified lines
195 }196 minIdx = util.Max(0, begin-1)197 for idx := begin; idx <= end; idx++ {198 if idx >= 1 && idx <= numTokens {198 part += *tokens[idx-1].text199 part = append(part, *tokens[idx-1].text...)200 }201 }202 }202 whole += part203 var prefixLength int204 if minIdx < numTokens {205 prefixLength = tokens[minIdx].prefixLength206 } else {207 prefixLength = 0208 }209 transTokens[idx] = Token{&part, prefixLength}210 }211 return &Transformed{212 whole: &whole,213 parts: transTokens}211 return &transTokens212}
modified:CHANGELOG.md+8 added
1CHANGELOG2=========340.9.105------67### Improvements89- Performance optimization10- Less aggressive memoization to limit memory usage11120.9.913-----1415### New features
132 unmodified lines