go-libp2p-peerstore/pstoremem/metadata.go

46 lines
899 B
Go
Raw Normal View History

2018-09-05 01:07:44 +08:00
package pstoremem
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"
)
2019-04-23 15:10:05 +08:00
type metakey struct {
id peer.ID
key string
}
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
}
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
func NewPeerMetadata() pstore.PeerMetadata {
return &memoryPeerMetadata{
2019-04-23 15:10:05 +08:00
ds: make(map[metakey]interface{}),
}
}
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
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}]
if !ok {
return nil, pstore.ErrNotFound
}
return i, nil
}