storage: simplify MemoryBatch

It's used a lot and it looks a lot like MemoryStore, it just needs not to
return errors from Put and Delete, so make it use MemoryStore internally with
adjusted interface.
This commit is contained in:
Roman Khimov 2019-10-07 20:25:33 +03:00
parent 13bf2618ef
commit 78861485b6
3 changed files with 7 additions and 18 deletions

View file

@ -83,7 +83,7 @@ func (s *BoltDBStore) Delete(key []byte) error {
func (s *BoltDBStore) PutBatch(batch Batch) error {
return s.db.Batch(func(tx *bbolt.Tx) error {
b := tx.Bucket(Bucket)
for k, v := range batch.(*MemoryBatch).m {
for k, v := range batch.(*MemoryBatch).mem {
err := b.Put([]byte(k), v)
if err != nil {
return err

View file

@ -16,25 +16,17 @@ type MemoryStore struct {
// MemoryBatch a in-memory batch compatible with MemoryStore.
type MemoryBatch struct {
m map[string][]byte
// A map, not a slice, to avoid duplicates.
del map[string]bool
MemoryStore
}
// Put implements the Batch interface.
func (b *MemoryBatch) Put(k, v []byte) {
vcopy := make([]byte, len(v))
copy(vcopy, v)
kcopy := string(k)
b.m[kcopy] = vcopy
delete(b.del, kcopy)
_ = b.MemoryStore.Put(k, v)
}
// Delete implements Batch interface.
func (b *MemoryBatch) Delete(k []byte) {
kcopy := string(k)
delete(b.m, kcopy)
b.del[kcopy] = true
_ = b.MemoryStore.Delete(k)
}
// NewMemoryStore creates a new MemoryStore object.
@ -97,7 +89,7 @@ func (s *MemoryStore) PutBatch(batch Batch) error {
for k := range b.del {
s.drop(k)
}
for k, v := range b.m {
for k, v := range b.mem {
s.put(k, v)
}
return nil
@ -119,10 +111,7 @@ func (s *MemoryStore) Batch() Batch {
// newMemoryBatch returns new memory batch.
func newMemoryBatch() *MemoryBatch {
return &MemoryBatch{
m: make(map[string][]byte),
del: make(map[string]bool),
}
return &MemoryBatch{MemoryStore: *NewMemoryStore()}
}
// Persist flushes all the MemoryStore contents into the (supposedly) persistent

View file

@ -63,7 +63,7 @@ func (s *RedisStore) Put(k, v []byte) error {
// PutBatch implements the Store interface.
func (s *RedisStore) PutBatch(b Batch) error {
pipe := s.client.Pipeline()
for k, v := range b.(*MemoryBatch).m {
for k, v := range b.(*MemoryBatch).mem {
pipe.Set(k, v, 0)
}
for k := range b.(*MemoryBatch).del {