Add RemoveAll and Visit functions to kv store

This commit is contained in:
Steve Streeting 2016-12-05 16:44:02 +00:00
parent 7ac855b684
commit eccfa781ae
2 changed files with 50 additions and 0 deletions

@ -71,6 +71,33 @@ func (k *Store) Remove(key string) {
k.logChange(removeOperation, key, nil)
}
// RemoveAll removes all entries from the store
// These changes are not persisted until you call Save()
func (k *Store) RemoveAll() {
k.mu.Lock()
defer k.mu.Unlock()
// Log all changes
for key, _ := range k.db {
k.logChange(removeOperation, key, nil)
}
k.db = make(map[string]interface{})
}
// Visit walks through the entire store via a function; return false from
// your visitor function to halt the walk
func (k *Store) Visit(cb func(string, interface{}) bool) {
// Read-only lock
k.mu.RLock()
defer k.mu.RUnlock()
for k, v := range k.db {
if !cb(k, v) {
break
}
}
}
// Append a change to the log; mutex must already be locked
func (k *Store) logChange(op operation, key string, value interface{}) {
k.log = append(k.log, change{op, key, value})

@ -66,6 +66,29 @@ func TestStoreSimple(t *testing.T) {
n = kvs2.Get("noValue")
assert.Nil(t, n)
// Test remove all
kvs2.RemoveAll()
s = kvs2.Get("stringVal")
assert.Nil(t, s)
i = kvs2.Get("intVal")
assert.Nil(t, i)
f = kvs2.Get("floatVal")
assert.Nil(t, f)
c = kvs2.Get("structVal")
assert.Nil(t, c)
err = kvs2.Save()
assert.Nil(t, err)
kvs2 = nil
// Now confirm that we can read blank & get nothing
kvs, err = NewStore(filename)
kvs.Visit(func(k string, v interface{}) bool {
// Should not be called
assert.Fail(t, "Should be no entries")
return true
})
}
func TestStoreOptimisticConflict(t *testing.T) {