status-go/vendor/github.com/libp2p/go-libp2p-peerstore/pstoremem/metadata.go

66 lines
1.3 KiB
Go
Raw Normal View History

2019-06-09 07:24:20 +00:00
package pstoremem
import (
"sync"
peer "github.com/libp2p/go-libp2p-core/peer"
pstore "github.com/libp2p/go-libp2p-core/peerstore"
2019-06-09 07:24:20 +00:00
)
var internKeys = map[string]bool{
"AgentVersion": true,
"ProtocolVersion": true,
}
2019-06-09 07:24:20 +00:00
type metakey struct {
id peer.ID
key string
}
type memoryPeerMetadata struct {
// store other data, like versions
//ds ds.ThreadSafeDatastore
ds map[metakey]interface{}
dslock sync.RWMutex
interned map[string]interface{}
2019-06-09 07:24:20 +00:00
}
var _ pstore.PeerMetadata = (*memoryPeerMetadata)(nil)
func NewPeerMetadata() *memoryPeerMetadata {
2019-06-09 07:24:20 +00:00
return &memoryPeerMetadata{
ds: make(map[metakey]interface{}),
interned: make(map[string]interface{}),
2019-06-09 07:24:20 +00:00
}
}
func (ps *memoryPeerMetadata) Put(p peer.ID, key string, val interface{}) error {
if err := p.Validate(); err != nil {
return err
}
2019-06-09 07:24:20 +00:00
ps.dslock.Lock()
defer ps.dslock.Unlock()
if vals, ok := val.(string); ok && internKeys[key] {
if interned, ok := ps.interned[vals]; ok {
val = interned
} else {
ps.interned[vals] = val
}
}
2019-06-09 07:24:20 +00:00
ps.ds[metakey{p, key}] = val
return nil
}
func (ps *memoryPeerMetadata) Get(p peer.ID, key string) (interface{}, error) {
if err := p.Validate(); err != nil {
return nil, err
}
2019-06-09 07:24:20 +00:00
ps.dslock.RLock()
defer ps.dslock.RUnlock()
i, ok := ps.ds[metakey{p, key}]
if !ok {
return nil, pstore.ErrNotFound
}
return i, nil
}