2018-09-05 01:07:44 +08:00
|
|
|
package pstoremem
|
2018-08-29 22:12:41 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
2018-09-08 01:46:23 +08:00
|
|
|
peer "github.com/libp2p/go-libp2p-peer"
|
2018-08-30 23:24:09 +08:00
|
|
|
pstore "github.com/libp2p/go-libp2p-peerstore"
|
2018-08-29 22:12:41 +08:00
|
|
|
)
|
|
|
|
|
2019-04-23 15:10:05 +08:00
|
|
|
type metakey struct {
|
|
|
|
id peer.ID
|
|
|
|
key string
|
|
|
|
}
|
|
|
|
|
2018-08-29 22:12:41 +08:00
|
|
|
type memoryPeerMetadata struct {
|
|
|
|
// store other data, like versions
|
|
|
|
//ds ds.ThreadSafeDatastore
|
2019-04-23 15:10:05 +08:00
|
|
|
ds map[metakey]interface{}
|
2019-04-28 03:19:49 +08:00
|
|
|
dslock sync.RWMutex
|
2018-08-29 22:12:41 +08:00
|
|
|
}
|
|
|
|
|
2018-09-28 21:04:52 +08:00
|
|
|
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
|
|
|
|
|
2018-08-30 21:13:27 +08:00
|
|
|
func NewPeerMetadata() pstore.PeerMetadata {
|
2018-08-29 22:12:41 +08:00
|
|
|
return &memoryPeerMetadata{
|
2019-04-23 15:10:05 +08:00
|
|
|
ds: make(map[metakey]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()
|
2019-04-23 15:10:05 +08:00
|
|
|
ps.ds[metakey{p, 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()
|
2019-04-23 15:10:05 +08:00
|
|
|
i, ok := ps.ds[metakey{p, 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
|
|
|
}
|
|
|
|
return i, nil
|
|
|
|
}
|