Skip to content

Commit

Permalink
refactor: embed mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
radulucut committed Jun 21, 2024
1 parent 15679e0 commit 88feefc
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions search.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,47 @@ import (
)

type Engine struct {
sync.RWMutex
items map[int64][][]rune
tokenize TokenizeFunc
tolerance int
mx sync.RWMutex
}

func NewEngine() *Engine {
engine := &Engine{
items: make(map[int64][][]rune),
tolerance: 1,
tokenize: Tokenize,
mx: sync.RWMutex{},
}
return engine
}

// Set custom tokenize function.
func (e *Engine) SetTokenizeFunc(f TokenizeFunc) {
e.mx.Lock()
defer e.mx.Unlock()
e.Lock()
defer e.Unlock()
e.tokenize = f
}

// Set the maximum number of typos per word allowed.
// The default value is 1.
func (e *Engine) SetTolerance(tolerance int) {
e.mx.Lock()
defer e.mx.Unlock()
e.Lock()
defer e.Unlock()
e.tolerance = tolerance
}

// Add a new item to the search engine.
func (e *Engine) SetItem(id int64, text string) {
e.mx.Lock()
defer e.mx.Unlock()
e.Lock()
defer e.Unlock()
e.items[id] = e.tokenize(text)
}

// Remove an item from the search engine.
func (e *Engine) DeleteItem(id int64) {
e.mx.Lock()
defer e.mx.Unlock()
e.Lock()
defer e.Unlock()
delete(e.items, id)
}

Expand All @@ -71,8 +70,8 @@ func (e *Engine) Search(query string, limit int, ignore []int64) []int64 {
}

q := e.tokenize(query)
e.mx.RLock()
defer e.mx.RUnlock()
e.RLock()
defer e.RUnlock()
scores := make([]itemScore, 0)
for id := range e.items {
if hasIgnore {
Expand Down

0 comments on commit 88feefc

Please sign in to comment.