Message.go 1.21 KB
Newer Older
1 2
package dht

Jeromy's avatar
Jeromy committed
3
import (
Jeromy's avatar
Jeromy committed
4
	"code.google.com/p/goprotobuf/proto"
Jeromy's avatar
Jeromy committed
5 6 7
	peer "github.com/jbenet/go-ipfs/peer"
)

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

func peerInfo(p *peer.Peer) *PBDHTMessage_PBPeer {
	pbp := new(PBDHTMessage_PBPeer)
Jeromy's avatar
Jeromy committed
21 22 23 24 25 26 27 28 29
	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
Jeromy's avatar
Jeromy committed
30 31 32 33
	}
	pid := string(p.ID)
	pbp.Id = &pid
	return pbp
34 35
}

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

	pmes.Type = &m.Type
	pmes.Key = &m.Key
	pmes.Response = &m.Response
48
	pmes.Id = &m.ID
49
	pmes.Success = &m.Success
Jeromy's avatar
Jeromy committed
50 51 52
	for _, p := range m.Peers {
		pmes.Peers = append(pmes.Peers, peerInfo(p))
	}
53 54 55

	return pmes
}