prysm-pulse/sharding/database/inmemory.go
Raul Jordan d5a991c2b4 sharding: made inmemory db concurrency-safe
Former-commit-id: 479801ca87e72986b2e635839c2e178cd08e7c8d [formerly 154c4c2fb0fa8dbaf24be0b8daf428c7f0c061b0]
Former-commit-id: 6489659f940b3737c663c40ff3f5385d001f5b97
2018-05-22 11:42:31 -04:00

56 lines
1.3 KiB
Go

// Package database provides several constructs including a simple in-memory database.
// This should not be used for production, but would be a helpful interim
// solution for development.
package database
import (
"fmt"
"sync"
"github.com/ethereum/go-ethereum/common"
)
// ShardKV is an in-memory mapping of hashes to RLP encoded values.
type ShardKV struct {
kv map[common.Hash]*[]byte
lock sync.RWMutex
}
// NewShardKV initializes a keyval store in memory.
func NewShardKV() *ShardKV {
return &ShardKV{kv: make(map[common.Hash]*[]byte)}
}
// Get fetches a val from the mappping by key.
func (sb *ShardKV) Get(k common.Hash) (*[]byte, error) {
v, ok := sb.kv[k]
if !ok {
return nil, fmt.Errorf("key not found: %v", k)
}
return v, nil
}
// Has checks if the key exists in the mapping.
func (sb *ShardKV) Has(k common.Hash) bool {
v := sb.kv[k]
return v != nil
}
// Put updates a key's value in the mapping.
func (sb *ShardKV) Put(k common.Hash, v []byte) error {
sb.lock.Lock()
defer sb.lock.Unlock()
// there is no error in a simple setting of a value in a go map.
sb.kv[k] = &v
return nil
}
// Delete removes the key and value from the mapping.
func (sb *ShardKV) Delete(k common.Hash) error {
sb.lock.Lock()
defer sb.lock.Unlock()
// There is no return value for deleting a simple key in a go map.
delete(sb.kv, k)
return nil
}