Skip to content

Commit

Permalink
use RWMutex
Browse files Browse the repository at this point in the history
  • Loading branch information
ktr0731 committed Feb 8, 2019
1 parent d5a11ff commit 54671df
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
24 changes: 13 additions & 11 deletions fuzzyfinder.go
Expand Up @@ -60,7 +60,7 @@ type state struct {

type finder struct {
term terminal
stateMu sync.Mutex
stateMu sync.RWMutex
state state
drawTimer *time.Timer
opt *opt
Expand Down Expand Up @@ -88,12 +88,14 @@ func (f *finder) initFinder(items []string, matched []matching.Matched, opts []O
f.state.items = items
f.state.matched = matched
f.state.allMatched = matched
f.drawTimer = time.AfterFunc(0, func() {
f._draw()
f._drawPreview()
f.term.flush()
})
f.drawTimer.Stop()
if !isInTesting() {
f.drawTimer = time.AfterFunc(0, func() {
f._draw()
f._drawPreview()
f.term.flush()
})
f.drawTimer.Stop()
}
return nil
}

Expand Down Expand Up @@ -270,8 +272,8 @@ func (f *finder) _drawPreview() {
}

func (f *finder) draw(d time.Duration) {
f.stateMu.Lock()
defer f.stateMu.Unlock()
f.stateMu.RLock()
defer f.stateMu.RUnlock()

if isInTesting() {
// Don't use goroutine scheduling.
Expand Down Expand Up @@ -481,8 +483,8 @@ func (f *finder) find(slice interface{}, itemFunc func(i int) string, opts []Opt
case err == ErrAbort:
return nil, ErrAbort
case err == errEntered:
f.stateMu.Lock()
defer f.stateMu.Unlock()
f.stateMu.RLock()
defer f.stateMu.RUnlock()

if len(f.state.matched) == 0 {
return nil, ErrAbort
Expand Down
6 changes: 4 additions & 2 deletions fuzzyfinder_test.go
Expand Up @@ -197,14 +197,16 @@ func TestFind_enter(t *testing.T) {

func TestFind_error(t *testing.T) {
t.Run("not a slice", func(t *testing.T) {
_, err := fuzzyfinder.Find("", func(i int) string { return "" })
f := fuzzyfinder.New()
_, err := f.Find("", func(i int) string { return "" })
if err == nil {
t.Error("Find must return an error, but got nil")
}
})

t.Run("itemFunc is nil", func(t *testing.T) {
_, err := fuzzyfinder.Find([]string{}, nil)
f := fuzzyfinder.New()
_, err := f.Find([]string{}, nil)
if err == nil {
t.Error("Find must return an error, but got nil")
}
Expand Down
6 changes: 5 additions & 1 deletion helper_test.go
@@ -1,7 +1,11 @@
package fuzzyfinder

func New() *finder {
return &finder{}
}

func NewWithMockedTerminal() (*finder, *TerminalMock) {
f := &finder{}
f := New()
m := f.UseMockedTerminal()
w, h := 60, 10 // A normally value.
m.SetSize(w, h)
Expand Down

0 comments on commit 54671df

Please sign in to comment.