Message.go 1.08 KB
Newer Older
1 2
package dht

Jeromy's avatar
Jeromy committed
3 4 5 6
import (
	peer "github.com/jbenet/go-ipfs/peer"
)

7 8
// Message is a a helper struct which makes working with protbuf types easier
type Message struct {
9 10 11
	Type     PBDHTMessage_MessageType
	Key      string
	Value    []byte
12
	Response bool
13
	ID       uint64
14
	Success  bool
Jeromy's avatar
Jeromy committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28
	Peers    []*peer.Peer
}

func peerInfo(p *peer.Peer) *PBDHTMessage_PBPeer {
	pbp := new(PBDHTMessage_PBPeer)
	addr, err := p.Addresses[0].String()
	if err != nil {
		//Temp: what situations could cause this?
		panic(err)
	}
	pbp.Addr = &addr
	pid := string(p.ID)
	pbp.Id = &pid
	return pbp
29 30
}

31
// ToProtobuf takes a Message and produces a protobuf with it.
32 33
// TODO: building the protobuf message this way is a little wasteful
//		 Unused fields wont be omitted, find a better way to do this
34
func (m *Message) ToProtobuf() *PBDHTMessage {
35
	pmes := new(PBDHTMessage)
36 37 38 39 40 41 42
	if m.Value != nil {
		pmes.Value = m.Value
	}

	pmes.Type = &m.Type
	pmes.Key = &m.Key
	pmes.Response = &m.Response
43
	pmes.Id = &m.ID
44
	pmes.Success = &m.Success
Jeromy's avatar
Jeromy committed
45 46 47
	for _, p := range m.Peers {
		pmes.Peers = append(pmes.Peers, peerInfo(p))
	}
48 49 50

	return pmes
}