Use channel to receive list of runes insteard of raw array access

This commit is contained in:
Daisuke Maki 2016-07-05 16:03:13 +09:00
parent 622671ef4d
commit 79556d5ad1
2 changed files with 17 additions and 8 deletions

View file

@ -154,7 +154,8 @@ func (u UserPrompt) Draw(state *Peco) {
default:
// the caret is in the middle of the string
prev := int(0)
for i, r := range q.Runes() {
var i int
for r := range q.Runes() {
fg := u.styles.Query.fg
bg := u.styles.Query.bg
if i == c.Pos() {
@ -163,6 +164,7 @@ func (u UserPrompt) Draw(state *Peco) {
}
u.screen.SetCell(int(u.promptLen+1+prev), int(location), r, fg, bg)
prev += int(runewidth.RuneWidth(r))
i++
}
fg := u.styles.Query.fg
bg := u.styles.Query.bg

View file

@ -69,16 +69,23 @@ func (q *Query) Append(r rune) {
q.query = append(q.query, r)
}
// Runes returns a copy of the underlying query as an array of runes.
func (q *Query) Runes() []rune {
// Runes returns a channel that gives you the list of runes in the query
func (q *Query) Runes() <-chan rune {
q.mutex.Lock()
defer q.mutex.Unlock()
ret := make([]rune, len(q.query))
copy(ret, q.query)
c := make(chan rune, len(q.query))
// Because this is a copy, the user of this function does not need
// to know about locking and stuff
return ret
go func() {
defer close(c)
q.mutex.Lock()
defer q.mutex.Unlock()
for _, r := range q.query {
c<-r
}
}()
return c
}
func (q *Query) RuneAt(where int) rune {