github.com/elves/elvish@v0.15.0/pkg/cli/histutil/mem_store.go (about)

     1  package histutil
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/elves/elvish/pkg/store"
     7  )
     8  
     9  // NewMemStore returns a Store that stores command history in memory.
    10  func NewMemStore(texts ...string) Store {
    11  	cmds := make([]store.Cmd, len(texts))
    12  	for i, text := range texts {
    13  		cmds[i] = store.Cmd{Text: text, Seq: i}
    14  	}
    15  	return &memStore{cmds}
    16  }
    17  
    18  type memStore struct{ cmds []store.Cmd }
    19  
    20  func (s *memStore) AllCmds() ([]store.Cmd, error) {
    21  	return s.cmds, nil
    22  }
    23  
    24  func (s *memStore) AddCmd(cmd store.Cmd) (int, error) {
    25  	if cmd.Seq < 0 {
    26  		cmd.Seq = len(s.cmds) + 1
    27  	}
    28  	s.cmds = append(s.cmds, cmd)
    29  	return cmd.Seq, nil
    30  }
    31  
    32  func (s *memStore) Cursor(prefix string) Cursor {
    33  	return &memStoreCursor{s.cmds, prefix, len(s.cmds)}
    34  }
    35  
    36  type memStoreCursor struct {
    37  	cmds   []store.Cmd
    38  	prefix string
    39  	index  int
    40  }
    41  
    42  func (c *memStoreCursor) Prev() {
    43  	if c.index < 0 {
    44  		return
    45  	}
    46  	for c.index--; c.index >= 0; c.index-- {
    47  		if strings.HasPrefix(c.cmds[c.index].Text, c.prefix) {
    48  			return
    49  		}
    50  	}
    51  }
    52  
    53  func (c *memStoreCursor) Next() {
    54  	if c.index >= len(c.cmds) {
    55  		return
    56  	}
    57  	for c.index++; c.index < len(c.cmds); c.index++ {
    58  		if strings.HasPrefix(c.cmds[c.index].Text, c.prefix) {
    59  			return
    60  		}
    61  	}
    62  }
    63  
    64  func (c *memStoreCursor) Get() (store.Cmd, error) {
    65  	if c.index < 0 || c.index >= len(c.cmds) {
    66  		return store.Cmd{}, ErrEndOfHistory
    67  	}
    68  	return c.cmds[c.index], nil
    69  }