2018-09-05 01:07:44 +08:00
|
|
|
package pstoremem
|
2018-08-29 22:12:41 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2021-10-23 17:46:51 +08:00
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
2019-05-31 21:51:16 +08:00
|
|
|
pstore "github.com/libp2p/go-libp2p-core/peerstore"
|
2018-08-29 22:12:41 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type memoryPeerMetadata struct {
|
|
|
|
// store other data, like versions
|
2021-12-02 18:11:27 +08:00
|
|
|
ds map[peer.ID]map[string]interface{}
|
|
|
|
dslock sync.RWMutex
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
|
2018-09-28 21:04:52 +08:00
|
|
|
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
|
|
|
|
|
2020-03-06 20:07:36 +08:00
|
|
|
func NewPeerMetadata() *memoryPeerMetadata {
|
2018-08-29 22:12:41 +08:00
|
|
|
return &memoryPeerMetadata{
|
2021-12-02 18:11:27 +08:00
|
|
|
ds: make(map[peer.ID]map[string]interface{}),
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Put(p peer.ID, key string, val interface{}) error {
|
|
|
|
ps.dslock.Lock()
|
|
|
|
defer ps.dslock.Unlock()
|
2021-10-23 17:51:31 +08:00
|
|
|
m, ok := ps.ds[p]
|
|
|
|
if !ok {
|
|
|
|
m = make(map[string]interface{})
|
|
|
|
ps.ds[p] = m
|
|
|
|
}
|
|
|
|
m[key] = val
|
2018-08-29 22:12:41 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) Get(p peer.ID, key string) (interface{}, error) {
|
2019-04-28 03:19:49 +08:00
|
|
|
ps.dslock.RLock()
|
|
|
|
defer ps.dslock.RUnlock()
|
2021-10-23 17:51:31 +08:00
|
|
|
m, ok := ps.ds[p]
|
|
|
|
if !ok {
|
|
|
|
return nil, pstore.ErrNotFound
|
|
|
|
}
|
|
|
|
val, ok := m[key]
|
2018-08-29 22:12:41 +08:00
|
|
|
if !ok {
|
2018-08-30 21:13:27 +08:00
|
|
|
return nil, pstore.ErrNotFound
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
2021-10-23 17:51:31 +08:00
|
|
|
return val, nil
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
2021-10-23 20:31:58 +08:00
|
|
|
|
|
|
|
func (ps *memoryPeerMetadata) RemovePeer(p peer.ID) {
|
|
|
|
ps.dslock.Lock()
|
|
|
|
delete(ps.ds, p)
|
|
|
|
ps.dslock.Unlock()
|
|
|
|
}
|