Skip to content

Commit

Permalink
add lock to memory storage
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Riedel committed Aug 28, 2019
1 parent 8e48e0e commit 3fc95a8
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions storage/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"strings"
"sync"

"github.com/syndtr/goleveldb/leveldb/util"
)
Expand Down Expand Up @@ -70,6 +71,8 @@ type memory struct {
storage map[string][]byte
offset *int64
recovered bool
// mutex to protect map reads/writes
rwm sync.RWMutex
}

// NewMemory returns a new in-memory storage.
Expand All @@ -81,25 +84,33 @@ func NewMemory() Storage {
}

func (m *memory) Has(key string) (bool, error) {
m.rwm.RLock()
_, has := m.storage[key]
m.rwm.RUnlock()
return has, nil
}

func (m *memory) Get(key string) ([]byte, error) {
m.rwm.RLock()
value, _ := m.storage[key]
m.rwm.RUnlock()
return value, nil
}

func (m *memory) Set(key string, value []byte) error {
if value == nil {
return fmt.Errorf("cannot write nil value")
}
m.rwm.Lock()
m.storage[key] = value
m.rwm.Unlock()
return nil
}

func (m *memory) Delete(key string) error {
m.rwm.Lock()
delete(m.storage, key)
m.rwm.Unlock()
return nil
}

Expand Down

0 comments on commit 3fc95a8

Please sign in to comment.