package memdb

import (
	"sync"

	"github.com/exchain/go-exchain/metadb"
)

type syncmapdb struct {
	db sync.Map
}

func (s *syncmapdb) Get(key interface{}) (interface{}, bool) {
	v, ok := s.db.Load(key)
	if !ok {
		return nil, false
	} else {
		return v, true
	}
}

func (s *syncmapdb) Set(key, value interface{}) error {
	s.db.Store(key, value)
	return nil
}

func (s *syncmapdb) Delete(key interface{}) error {
	s.db.Delete(key)
	return nil
}

func (s *syncmapdb) Copy() metadb.CacheKV {
	nd := NewMemDB()
	s.db.Range(func(k, v interface{}) bool {
		nd.Set(k, v)
		return true
	})
	return nd
}

func NewMemDB() metadb.CacheKV {
	return &syncmapdb{}
}
