go-libp2p-kad-dht/Message.go

56 lines
1.2 KiB
Go
Raw Normal View History

package dht
2014-08-09 22:28:46 -07:00
import (
2014-08-19 19:14:52 -07:00
"code.google.com/p/goprotobuf/proto"
2014-08-09 22:28:46 -07:00
peer "github.com/jbenet/go-ipfs/peer"
)
2014-08-16 23:03:36 -07:00
// Message is a a helper struct which makes working with protbuf types easier
type Message struct {
Type PBDHTMessage_MessageType
Key string
Value []byte
Response bool
ID string
Success bool
2014-08-09 22:28:46 -07:00
Peers []*peer.Peer
}
func peerInfo(p *peer.Peer) *PBDHTMessage_PBPeer {
pbp := new(PBDHTMessage_PBPeer)
2014-08-19 19:14:52 -07:00
if len(p.Addresses) == 0 || p.Addresses[0] == nil {
pbp.Addr = proto.String("")
} else {
addr, err := p.Addresses[0].String()
if err != nil {
//Temp: what situations could cause this?
panic(err)
}
pbp.Addr = &addr
2014-08-09 22:28:46 -07:00
}
pid := string(p.ID)
pbp.Id = &pid
return pbp
}
2014-08-16 23:03:36 -07:00
// ToProtobuf takes a Message and produces a protobuf with it.
// TODO: building the protobuf message this way is a little wasteful
// Unused fields wont be omitted, find a better way to do this
2014-08-16 23:03:36 -07:00
func (m *Message) ToProtobuf() *PBDHTMessage {
pmes := new(PBDHTMessage)
if m.Value != nil {
pmes.Value = m.Value
}
pmes.Type = &m.Type
pmes.Key = &m.Key
pmes.Response = &m.Response
2014-08-16 23:03:36 -07:00
pmes.Id = &m.ID
pmes.Success = &m.Success
2014-08-09 22:28:46 -07:00
for _, p := range m.Peers {
pmes.Peers = append(pmes.Peers, peerInfo(p))
}
return pmes
}